与ggplot2共面的饼图

时间:2013-08-30 16:16:01

标签: r ggplot2 pie-chart

我用ggplot2做了一个多面的饼图:

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

enter image description here

但由于所有的饼图共享y轴刻度,其中一些不覆盖整个圆圈。我试过facet_grid(~gear, scales="free")但它不起作用。

我怎么能得到所有饼图的完整圆圈?

2 个答案:

答案 0 :(得分:10)

我想你只想要position = 'fill'

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

供将来参考,来自geom_bar的详细信息部分:

  

默认情况下,在同一个地方发生的多个x将被堆叠起来   通过position_stack互相排在第一位。如果你想让它们被躲避   并排,见position_dodge。最后,position_fill显示   通过堆叠条然后拉伸每个x的相对比例   或挤压到相同的高度。

答案 1 :(得分:0)

如果您正在寻找另一种方便的方法,可以查看ggstatsplot软件包,包括条形图和饼图。

# 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

reprex package(v0.3.0)于2019-06-23创建