我有三个变量的频率计数,并希望在饼图中显示频率计数。我尝试了 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)
但是,我想要这样的东西:
如何重置每个面板中的颜色?
您必须引入一个在每个方面都相同的虚拟变量:
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')条线,因此情节实际上看起来像您制作的情节。