faceted piechart with ggplot2

江枫思渺然 提交于 2019-12-17 20:28:58

问题


I've done a faceted piechart with ggplot2 like this:

qplot(x=factor(1), data=mtcars, fill=factor(cyl)) + 
    geom_bar(width=1) +  
    coord_polar(theta="y") + 
    facet_grid(~gear)

but as all the piecharts share the y axis scale, some of them doesn't cover the full circle. I've tried with facet_grid(~gear, scales="free") but it doesn't work.

How could I get full circles for all the piecharts?


回答1:


I think you just want position = 'fill':

ggplot(mtcars,aes(x = factor(1),fill=factor(cyl))) + 
    facet_wrap(~gear) + 
    geom_bar(width = 1,position = "fill") + 
    coord_polar(theta="y")

For future reference, from the Details section of geom_bar:

By default, multiple x's occuring in the same place will be stacked a top one another by position_stack. If you want them to be dodged from side-to-side, see position_dodge. Finally, position_fill shows relative propotions at each x by stacking the bars and then stretching or squashing to the same height.




回答2:


If you are looking for another convenient way to do this, you can have a look at the ggstatsplot package, both the bar and the pie charts.

# setup
set.seed(123)
library(ggstatsplot)

# pie chart
ggpiestats(mtcars, gear, cyl)

#> Warning in stats::chisq.test(x = data$main, y = data$condition, correct =
#> FALSE, : Chi-squared approximation may be incorrect

# bar chart
ggbarstats(mtcars, gear, cyl)
#> Warning in stats::chisq.test(x = data$main, y = data$condition, correct =
#> FALSE, : Chi-squared approximation may be incorrect

Created on 2019-06-23 by the reprex package (v0.3.0)



来源:https://stackoverflow.com/questions/18537378/faceted-piechart-with-ggplot2

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