繁体   English   中英

ggplot R中geom_bar中离散值的自定义颜色

[英]Custom colors for discrete values in geom_bar in ggplot R

我正在将带有计数的直方图转换为比例图。 我想让左边的七列变成绿色(x 值 0-6),接下来的两列是橙色的(7,8),右边的列(9 和 10)是红色的。

我试图遵循此线程中的方法,但颜色对我来说似乎有点随意。

我在使用我尝试过的其他方法将连续应用于离散变量时遇到错误。 有任何想法吗?

阴谋

df <- df <- data_frame( x = c(0,1,2,3,4,5,6,7,8,9,10), n = c(754, 300, 304, 390, 460, 1550, 1450, 4500, 6100, 9000, 14000))
#data
df<-df
 group_by(x) %>%
  summarise(n = n()) %>% 
  mutate(
    freq=(n/sum(n)),
    freq=round(100*freq, 2))

#set colors
colors <- c(rep("green",7), rep("orange",2), rep("red",2))

#plot
bar1<- ggplot(data=df, aes(x=x, y=freq, fill=colors))+
    geom_bar(stat="identity")+
    scale_y_continuous(labels=scales::percent) +
 geom_text(aes(label = scales::percent(freq)), vjust= -0.25, size=4)+
  ylab("Proportion")+
   xlab("X")+
    scale_x_discrete(limits=0:11)+
  ggtitle("Title")+
   theme_minimal()+
     theme(legend.position = "none")+
theme(plot.title = element_text(hjust = 0.5))

bar1

您可以使用scale_fill_manual()并更改初始aes()调用中的填充:

#plot
ggplot(data=df, aes(x=x, y=freq, fill=as.factor(x)))+
  geom_bar(stat="identity")+
  scale_y_continuous(labels=scales::percent) +
  geom_text(aes(label = scales::percent(freq)), vjust= -0.25, size=4)+
  ylab("Proportion")+
  xlab("X")+
  scale_x_discrete(limits=0:11)+
  scale_fill_manual(values = colors) +
  ggtitle("Title")+
  theme_minimal()+
  theme(legend.position = "none")+
  theme(plot.title = element_text(hjust = 0.5))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM