Flip coords for ggplot2 boxplot

心已入冬 提交于 2019-12-13 06:45:58

问题


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.



来源:https://stackoverflow.com/questions/34954247/flip-coords-for-ggplot2-boxplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!