Home > OS >  How to put label on histogram bin
How to put label on histogram bin

Time:02-16

Using mpg data from R studio, I want to make a join histogram and density graphic. The code that I used are

mpg %>%
  ggplot(aes(x = cty))  
  guides(fill='none')  
  xlab('Fuel Consumption in City Area')  
  geom_histogram(aes(y=..density..), binwidth = 50, fill='#3ba7c4')  
  geom_density(alpha=0.2)

And the result is this enter image description here

Because the Y axis no longer show the count of cty, I want to put label on top of every bin. The code that I used are

mpg %>%
  ggplot(aes(x = cty))  
  guides(fill='none')  
  xlab('Fuel Consumption in City Area')  
  geom_histogram(aes(y=..density..), binwidth = 50, fill='#3ba7c4')  
  stat_bin(binwidth=1, geom='text', color='black', aes(label=..count..), position=position_stack(vjust = 0.5))  
  geom_density(alpha=0.2)

But the graphic now only show the label without histogram and density graph enter image description here

How to fix this?

CodePudding user response:

You can use stat = "bin" inside geom_text. Use stat(density) for the y axis values, and stat(count) for the label aesthetic. Nudge the text upwards with a small negative vjust to make the counts sit on top of the bars.

mpg %>%
  ggplot(aes(x = cty))  
  guides(fill = 'none')  
  xlab('Fuel Consumption in City Area')  
  geom_histogram(aes(y = stat(density)), binwidth = 50, fill = '#3ba7c4')  
  geom_text(stat = "bin", aes(y = stat(density), label = stat(count)),
            binwidth = 50, vjust = -0.2)  
  geom_density(alpha = 0.2)

enter image description here

In reality you would want more bins, and to make the density line less opaque so it does not clash too much with the labels.

mpg %>%
  ggplot(aes(x = cty))  
  guides(fill = 'none')  
  xlab('Fuel Consumption in City Area')  
  geom_histogram(aes(y = stat(density)), binwidth = 5, fill = '#3ba7c4',
                 color = '#2898c0')  
  geom_text(stat = "bin", aes(y = stat(density), label = stat(count)),
            binwidth = 5, vjust = -0.2)  
  geom_density(color = alpha("black", 0.2))  
  theme_classic()

enter image description here

  • Related