ggplot中的饼图不是一个完整的圆圈

时间:2015-10-22 16:29:51

标签: r charts ggplot2 pie-chart

我正在尝试使用ggplot2生成饼图,该饼图显示指标变量中TRUEFALSE的比例。

flag <- sample(0:1, 100, replace = TRUE, prob = c(.2, .8))

我的第一次尝试使用:

gg_pie <- ggplot(data = as.data.frame(flag), aes(x = factor(1), fill = factor(flag)))
gg_pie <- gg_pie + geom_bar(width=1)
gg_pie <- gg_pie + coord_polar(theta = 'y')
gg_pie <- gg_pie + labs(x="", y="")
gg_pie <- gg_pie + scale_x_discrete(breaks=NULL) + scale_y_discrete(breaks=NULL)
gg_pie <- gg_pie + theme(panel.background = element_blank())
gg_pie

enter image description here

但是,由于Error in unit(tic_pos.c, "mm") : 'x' and 'units' must have length > 0错误,这样做不允许我在显示百分比的每个楔子上放置标签。因此,我尝试自己进行数字处理并传递长度为2的ggplot()数据。

df_pie <- as.data.frame(c(mean(flag), mean(!flag)))
names(df_pie) <- "ave_flag"
gg_pie <- ggplot(data = df_pie, aes(x = factor(1), fill = factor(ave_flag)))
gg_pie <- gg_pie + geom_bar(width=1)
gg_pie <- gg_pie + coord_polar(theta = 'y')
gg_pie <- gg_pie + labs(x="", y="")
gg_pie <- gg_pie + scale_x_discrete(breaks=NULL) + scale_y_discrete(breaks=NULL)
gg_pie <- gg_pie + theme(panel.background = element_blank())
gg_pie <- gg_pie + geom_text(aes(y = c(ave_flag[1]/2, ave_flag[1] + ave_flag[2]/2), label = ave_flag))
gg_pie

但是这给了我以下饼图,它显然已经在窗口上冷却了足够长的时间,以便当地的rapscallions能够拍几片。

enter image description here

我已尝试在此代码中更改任意数量的内容。我认为ggplot没有将因子级别识别为数字可能是一个问题,因此我尝试在传递给ave_penalty之前不将fill作为一个因素。但这只留下了一个单色圆圈。我尝试使用stat="identity"而不是binning,但这只是失败并出现错误。

任何人都可以建议一种方法(a)使第二个馅饼准确反映数据或(b)将两个标签放在第一个饼图上,即使问题中的数据长度不是2?

0 个答案:

没有答案