4

I have read in other questions with similar titles but have had no luck solving my problem. I have a dataframe with two columns: sales and size. sales is numeric, size is character with "Small (1-20)", "Medium (20-50)", "Large (50-100)" and "Extra Large (>200)". I would like to make a histogram where the bins widths are equal to the different sizes. with breaks= seq(.....) the interval is the same. Is there some way I can have different intervals in my bins using ggplot2?

I am sorry if this is a duplicate but I have really tried to find the answer in other questions and either this exact question haven't been posed or I am too stupid to understand the explanations.

mydf <- data.frame(
  Sales = c(301, 5, 4, 26, 19, 82, 111, 41, 29, 12),
  Size = c("Extra Large (>200)", "Small (1-20)", "Small (1-20)", "Medium (21-50)", 
      "Small (1-20)", "Large (51-200)", "Large (51-200)", 
      "Medium (21-50)", "Medium (21-50)", "Small (1-20)" ))

mydf %>% ggplot(aes(Sales))+geom_histogram(aes(y=..count..))

The histogram that is created need some band width adjustment and it's here I would like to use the "width" of the categories already described.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Mactilda
  • 393
  • 6
  • 18
  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. But what you are describing seems more like a bar chart than a histogram. – MrFlick Dec 03 '18 at 19:06
  • 2
    You can vary the widths for a histogram, but you'll need to make an actual histogram. `ggplot` will make a barplot if you have a categorical x-axis. – Axeman Dec 03 '18 at 19:08

1 Answers1

5

geom_histogram() will allows you to specify the breakpoints for your histogram. For example

mydf %>% ggplot(aes(Sales)) + 
  geom_histogram(breaks=c(0,20,50,200, 500))

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Yes thank you! There are so many questions and answers to browse trough and I've tried different things and nothing have worked out and I thought there've got to be an easier way. And there was! Again: Thanks. – Mactilda Dec 04 '18 at 16:00
  • Hi, related to this. Is it possible to make all the bins look like they are the same width? I would basically need to have 4 bins of the same appearance, although they do not represent the same range. Applied to this case, that would mean that all these bins would look like the first one, so the graph would be much smaller. Thanks a lot for any help – Antonio Feb 11 '22 at 11:16
  • @Antonio looooong time since you asked this, but I assume in the meantime you've realised you're just describing a bar chart? – Paul Stafford Allen Jun 23 '23 at 11:02