在ggplot2 R中每个分面重置颜色

3

我有三个变量的频率计数,想要在饼图中展示频率计数。我尝试使用ggplot并使用以下代码:

library(ggplot2)
df = data.frame(var = rep(c('a','b','c'),each = 3),
            class = letters[1:9],
            count = rep(1:3, 3))

ggplot(df, aes(x = '', y = count, fill = class)) + 
  geom_bar(width = 0.5, stat = 'identity') + 
  coord_polar('y', start = 10) + facet_wrap(~var) + 
  theme(legend.position = 'none')

我得到了以下图表: enter image description here 但是,我想要像这样的效果: enter image description here 如何在每个面板中重置颜色?

2
添加另一列。为其分配因子水平。将其用于“fill”美学。 - hrbrmstr
1个回答

5

您需要引入一个虚拟变量,使其在每个方面中都相同:

df = data.frame(var = rep(c('a','b','c'),each = 3),
                class = letters[1:9],
                dummy = rep(letters[1:3], 3),
                count = rep(1:3, 3))

ggplot(df, aes(x = '', y = count, fill = dummy)) + 
  geom_bar(width = 0.5, stat = 'identity') + 
  coord_polar('y', start = 10) + facet_wrap(~var)

enter image description here

我删除了 theme(legend.position = 'none') 这一行,这样图表就看起来和你制作的一样了。

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