重置每个方面的颜色 ggplot2 R

Jas*_*son 3 r ggplot2

我有三个变量的频率计数,并希望在饼图中显示频率计数。我尝试了 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')
Run Code Online (Sandbox Code Playgroud)

我得到以下图表: 在此处输入图片说明

但是,我想要这样的东西:

在此处输入图片说明

如何重置每个面板中的颜色?

Cla*_*lke 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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我删除了这theme(legend.position = 'none')条线,因此情节实际上看起来像您制作的情节。