用ggplot和for覆盖圆环图

用ggplot和for覆盖圆环图,r,for-loop,ggplot2,R,For Loop,Ggplot2,我最近开始使用R,我一直在尝试使用ggplot绘制一个包含几个甜甜圈的图形。 我的灵感来自于下面的问题——但我想用for循环创建几个戒指 我构建了一个测试数据框架,如下所示: library(ggplot2) # Create test data. rings<-data.frame(cat=c("A", "B", "C","D","E"), ring1=c(10, 60, 3, 70,5), ring2=c(20,30,8,15,1), ring3=c(5,40,80,22,10),

我最近开始使用R,我一直在尝试使用ggplot绘制一个包含几个甜甜圈的图形。 我的灵感来自于下面的问题——但我想用for循环创建几个戒指

我构建了一个测试数据框架,如下所示:

library(ggplot2)

# Create test data.
rings<-data.frame(cat=c("A", "B", "C","D","E"), ring1=c(10, 60, 3, 70,5), ring2=c(20,30,8,15,1), ring3=c(5,40,80,22,10), ring4=c(10,60,16,25,20) )

for (y in 2:5){
# Add addition columns, needed for drawing with geom_rect.
rings[[y]] =  rings[[y]] / sum(rings[[y]])
rings[[y]] = cumsum(rings[[y]])
}
库(ggplot2)
#创建测试数据。

ringsRule 1:永远不要使用饼图。推论:永远不要使用甜甜圈图表。它们为最大的图表空间提供了最少的信息。谢谢@CarlWitthoft,关于我应该使用的其他类型的可视化有什么建议吗?好的,你有什么样的数据,你想向你的观众发送什么信息?通常,人们使用条形图来显示不同类别或茎叶图的相对数量。
max<-4.5
min<-4

plot = ggplot(rings, aes(fill=cat, ymax=rings[[2]], ymin=c(0, head(rings[[2]], n=-1)), xmax=max, xmin=min)) +
geom_rect() +
coord_polar(theta="y") +
xlim(c(0, 10)) +
theme_bw() +
theme(panel.background = element_rect(fill = NA)) +
theme(panel.grid=element_blank()) +
theme(axis.text=element_blank()) +
theme(axis.ticks=element_blank()) +
labs(title="Customized ring plot")
plot <- plot + geom_rect(data=rings, xmax=max, xmin=min, aes(ymax=rings[[2]], ymin=c(0,   head(rings[[2]], n=-1))))
min<-max
max<-max+0.5
plot <- plot + geom_rect(data=rings, xmax=max, xmin=min, aes(ymax=rings[[3]], ymin=c(0,     head(rings[[3]], n=-1))))
min<-max
max<-max+0.5
plot <- plot + geom_rect(data=rings, xmax=max, xmin=min, aes(ymax=rings[[4]], ymin=c(0, head(rings[[4]], n=-1))))
min<-max
max<-max+0.5
plot <- plot + geom_rect(data=rings, xmax=max, xmin=min, aes(ymax=rings[[5]], ymin=c(0,  head(rings[[5]], n=-1))))

print(plot)
for (y in 3:5){
plot <- plot + geom_rect(data=rings, xmax=max, xmin=min, aes(ymax=rings[[y]], ymin=c(0, head(rings[[y]], n=-1))))
min<-max
max<-max+0.5
} 
print(plot)