在R中将条形图转换为饼图

3
我有以下数据和代码:

dd
  grp categ condition value
1   A     X         P     2
2   B     X         P     5
3   A     Y         P     9
4   B     Y         P     6
5   A     X         Q     4
6   B     X         Q     5
7   A     Y         Q     8
8   B     Y         Q     2
> 
> 
dput(dd)
structure(list(grp = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L), .Label = c("A", "B"), class = "factor"), categ = structure(c(1L, 
1L, 2L, 2L, 1L, 1L, 2L, 2L), .Label = c("X", "Y"), class = "factor"), 
    condition = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("P", 
    "Q"), class = "factor"), value = c(2, 5, 9, 6, 4, 5, 8, 2
    )), .Names = c("grp", "categ", "condition", "value"), out.attrs = structure(list(
    dim = structure(c(2L, 2L, 2L), .Names = c("grp", "categ", 
    "condition")), dimnames = structure(list(grp = c("grp=A", 
    "grp=B"), categ = c("categ=X", "categ=Y"), condition = c("condition=P", 
    "condition=Q")), .Names = c("grp", "categ", "condition"))), .Names = c("dim", 
"dimnames")), row.names = c(NA, -8L), class = "data.frame")


ggplot(dd, aes(grp,value, fill=condition))+geom_bar(stat='identity')+facet_grid(~categ)

enter image description here

如何将此条形图转换为饼图?我希望在这里有4个饼图,它们的大小对应于相应条形的高度。我尝试了以下方法,但它们没有起作用:

ggplot(dd, aes(grp,value, fill=condition))+geom_bar(stat='identity')+facet_grid(~categ)+coord_polar()
ggplot(dd, aes(grp,value, fill=condition))+geom_bar(stat='identity')+facet_grid(~categ)+coord_polar('y')

我也试图制作与ggplot2中可变饼图大小的饼图类似的饼图,但我无法处理我的数据。感谢您的帮助。


你想要一个饼图还是风向玫瑰图? - user3710546
我本来想做饼图,但一张能清晰传递信息的简单的风向玫瑰图也可以。 - rnso
2个回答

1

您希望将组和类别都作为网格的变量,而不是任何绘图内部的变量。这里有两种不同的布局。X应该是任何单个项目、字符串或其他内容。

ggplot(dd, aes(x=factor(1),y=value,
 fill=condition))+geom_bar(stat='identity')+
 facet_grid(~grp+categ)+coord_polar("x")
ggplot(dd, aes(x=factor(1),y=value,
 fill=condition))+geom_bar(stat='identity')+
 facet_grid(grp~categ)+coord_polar("x")

这里的顶部打开方式出了些问题,也许只是我的界面。但这应该足够帮助你继续进行!

Pie charts side by side

Pie charts in a square


1
使用您发布的链接中相同的想法,您可以为数据框添加一列“size”,该列将是每个组值的总和,并将其用作“width”参数:
library(dplyr)
dd<-dd %>% group_by(categ,grp) %>% mutate(size=sum(value))
ggplot(dd, aes(x=size/2,y=value,fill=condition,width=size))+geom_bar(position="fill",stat='identity')+facet_grid(grp~categ)+coord_polar("y")

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接