着色切片的饼条作为渐变在ggplot2

时间:2013-05-15 21:52:29

标签: r ggplot2 pie-chart

想象一下,我在ggplot2中有一个饼图,

data <- data.frame(cluster = paste("Cluster", 1:3), size = c(0.33, 0.33, 0.33))
data = rbind(data, data)

ggplot(data, aes(x = factor(1), fill = cluster, weight=size)) + 
  geom_bar(width = 1) + coord_polar(theta="y")+ theme_bw() + 
  scale_x_discrete("",breaks=NULL) + scale_y_continuous("",breaks=NULL) +
  theme(panel.border=element_blank(), 
        strip.text=element_blank(), 
        strip.background=element_blank(), 
        legend.position="none", 
        panel.grid=element_blank())

还有另一个强度向量,我用向量(0.2,-1,1)表示。我喜欢将每个切片着色为从蓝色到红色的渐变。比方说,蓝色,表示-1,红色表示1。

1 个答案:

答案 0 :(得分:1)

首先,我建议一个更清晰的数据框,一次包含所有数据,创建如下:

> data <- data.frame(cluster = paste("Cluster", 1:3), size = c(0.2, 0.3, 0.5), strength = c(0.2, -1, 1))
> data
    cluster size strength
1 Cluster 1  0.2      0.2
2 Cluster 2  0.3     -1.0
3 Cluster 3  0.5      1.0

然后,以下最小代码生成一个饼图,填充颜色在中点零点附近的比例上发散,具体取决于集群的强度值:

> ggplot(data, aes( x = factor(1), group = cluster, fill = strength, weight = size)) + geom_bar(width = 1) + coord_polar( theta = "y") + scale_fill_gradient2()

有关参考,请查看geom_bar文档页面中的scale_fill_gradient2文档页面示例: http://docs.ggplot2.org/current/scale_gradient2.html http://docs.ggplot2.org/current/geom_bar.html

相关问题