Home > database >  How to generate a faceted bar plot with reverse Y-axis and specified ylim in ggplot
How to generate a faceted bar plot with reverse Y-axis and specified ylim in ggplot

Time:09-22

I need help on how to generate a reversed stacked bar plot with specific ylim. I have used the code below for this purpose but the plot is generated in reverse order as expected but the ylim option did not work i.e, the y-axis labels were auto generated.

This is the data:

df <- structure(list(z = c("up", "up", "up", "up", "up", "up", "down", 
"down", "down", "down", "down", "down"), x = c("C", "C", "G", "G", "H", "H",
 "C", "C", "G", "G", "H", "H"), w = c("more", "less", "more", "less", "more", 
"less", "more", "less", "more", "less", "more", "less"), y = c(5, 6, 4, 4, 
50, 42, 50, 16, 24, 8, 83, 99)), class = c("tbl_df", "tbl", "data.frame"),
 row.names = c(NA, -12L)

My code is

ggplot(df, aes(x, y, fill=w)) geom_bar(stat='identity')  facet_wrap(~z, scales="free_y", ncol = 1)  xlab('a') ylab('b') theme(panel.background = element_blank(),axis.text = element_text(size = 8, color = 'black'), text = element_text(size = 8),plot.title = element_text(hjust = 0.5)) ggtitle('T')  ylim(0,500) scale_y_continuous(trans="reverse")

However, using the same code without reversing the plot generates a stacked plot in an upright position and with ylim as specified.

ggplot(df, aes(x, y, fill=w)) geom_bar(stat='identity')  facet_wrap(~z, scales="free_y", ncol = 1)  xlab('a') ylab('b') theme(panel.background = element_blank(),axis.text = element_text(size = 8, color = 'black'), text = element_text(size = 8),plot.title = element_text(hjust = 0.5)) ggtitle('T')  ylim(0,500)
 "scale_y_continuous(trans="reverse")", 

I need help on how to successfully generate this plot. Thanks

CodePudding user response:

You can use scale_y_reverse instead of scale_y_continuous with trans = "reverse". You can specify the limits using the limits argument rather than an extra call to ylim, and you need to specify the numbers from highest to lowest.

ggplot(df, aes(x, y, fill = w))  
  geom_col()   
  facet_wrap(~z, scales = "free_y", ncol = 1)  
  labs(x = 'a', y = "b", title = "T")  
  theme(panel.background = element_blank(),
        axis.text = element_text(size = 8, color = 'black'), 
        text = element_text(size = 8),
        plot.title = element_text(hjust = 0.5))   
   scale_y_reverse(limits = c(500, 0)) 

enter image description here

  • Related