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

问题描述 投票:0回答:1

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

我试图在该线程中遵循该方法,但是颜色似乎在随机再现。 How to manually fill colors in a ggplot2 histogram

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

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
r ggplot2 geom-bar aesthetics scale-color-manual
1个回答
0
投票

您可以使用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))
© www.soinside.com 2019 - 2024. All rights reserved.