0
trips_2021 %>% 
  ggplot(aes(x=factor(ride_month), fill = member_casual)) + geom_bar()+   #using factor() to display all x values
  scale_y_continuous(labels= comma) + 
  geom_text(stat = "count", aes(label = ..count..), size = 2)+
  theme(axis.text.x = element_text(angle = 90))+
  labs(title='Count of bike rides by months in 2021', x= 'Month of ride', y = 'Count of rides')

enter image description here

In the above image, we can clearly see that in some months say Jan, feb, oct and nov the data labels are incorrect and reversed (image shows that members take more rides than casual but their data labels tell otherwise). Whereas with the following code

trips_2021 %>% 
  ggplot(aes(x=factor(ride_month), fill = member_casual)) + geom_bar(position = 'fill')+   #using factor() to display all x values
  scale_y_continuous(labels= comma) + 
  geom_text(stat = "count", aes(label = ..count..), size = 2, position = 'fill')+
  theme(axis.text.x = element_text(angle = 90))+
  labs(title='Count of bike rides by months in 2021', x= 'Month of ride', y = 'Count of rides')

the plot is correct with correct data labels.

enter image description here

Why is this happening? Please explain!

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • The positions are correct in the second example because you have `position = 'fill'` in both the `geom_bar` and `geom_text` calls. In the first example, the positions are wrong because the default `position` for `geom_bar` is `position = 'stack'`, whereas for `geom_text` the default position is `position = 'identity'`. You need to specify `position = 'stack'` to the `geom_text` in your first example. – Allan Cameron Sep 01 '22 at 14:08
  • Have you seen this existing question? https://stackoverflow.com/questions/6644997/showing-data-values-on-stacked-bar-chart-in-ggplot2 – MrFlick Sep 01 '22 at 14:08

0 Answers0