Flip coords for ggplot2 boxplot

2019-09-05 07:51发布

问题:

I would like to flip the coords for a ggplot2 boxplot where I also do a coordinate transformation.

library(ggplot2)

dat = data.frame(group = factor(c(rep(1,3),rep(2,6))),
                 vals   = c(c(0.1,2.25,1000), c(0.11,0.21,0.21,4.55,5.06,29.48)))


   ggplot(dat,aes(group,vals)) + geom_boxplot() 
   ggplot(dat,aes(group,vals)) + geom_boxplot()  + coord_trans(y="log10")

If I just add now "+ coord_flip()", the log scaling of the axis is lost..

 ggplot(dat,aes(group,vals)) + geom_boxplot()  + coord_trans(y="log10") + coord_flip()

Any way to achieve flipping of coords?

Thanks for any comments!

Best, Stefanie

回答1:

maybe there is workaround. You can flip your plot using viewport(). EDIT: using package cowplot, you can switch the y axis.

library(ggplot2)
library(grid)
library(cowplot)
p <- ggplot(dat,aes(group,vals)) + geom_boxplot()  + coord_trans(y="log10") + theme(axis.text.x = element_text(angle = 90, hjust = 1), axis.title.x = element_text(angle = 90, hjust = 1), axis.text.y = element_text(angle = 90, hjust = 1))

pp <- ggdraw(switch_axis_position(p, axis = 'y'))

grid.newpage()
print(pp, vp = viewport(angle = -90, width = 0.7, height = 0.8))



回答2:

Just use scale_y_log10:

ggplot(dat,aes(group,vals)) + 
 geom_boxplot() + 
 coord_flip() + 
 scale_y_log10()

Then just adjust as needed.