简体   繁体   English

如何更改 ggplot 中条形图的 colors 保持图例变量相同?

[英]How to change the colors of a barplot in ggplot keeping legend variables same?

I would like to have a colorblind friendly paletter for a barplot in ggplot.我想为 ggplot 中的条形图提供一个色盲友好的调色板。 I plot the barplot through this code我通过此代码 plot 条形图

library(tidyverse)
my_se <- df %>%
  group_by(groups) %>%
  summarise(n=n(),
            sd=sd(mean),
            se=sd/sqrt(n))


    # Standard error
    df %>% 
      left_join(my_se) %>% 
      mutate(zone = factor(zone,labels = c("x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11"))) %>% 
      ggplot(aes(x=zone, y=mean, fill = groups)) + 
      geom_col(position = position_dodge()) +
      geom_errorbar(aes(x=zone, ymin=mean-se, ymax=mean+se), width=0.4, position = position_dodge(.9)) +
      ggtitle("using standard error")+scale_fill_discrete(labels = c("GC", "IP", "MR","CS"))+
      labs(y= an, x = "Land Cover")+theme_bw()+theme(legend.title =element_blank())+
      theme(legend.text=element_text(size=11),axis.text.y=element_text(size=11.5),
            axis.text.x=element_text(size=11.5),axis.title.x = element_text(size = 12), axis.title.y = element_text(size = 12))

I have made a custom color palette我制作了一个自定义调色板

cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#009E73")

But when I add this snippet code:但是当我添加这段代码时:

scale_fill_manual(values=cbPalette)

to my ggplot code it gives me this message对于我的 ggplot 代码,它给了我这个信息

Scale for 'fill' is already present. Adding another scale for 'fill', which
will replace the existing scale.

Although the colors are changed but my whole legend labels get changed with it.虽然 colors 发生了变化,但我的整个图例标签也随之改变。 I want to keep my legend variables as "GC", "IP", "MR","CS".我想将我的图例变量保留为“GC”、“IP”、“MR”、“CS”。

How can I change the colors of the bars with not effecting the legend labels of variables?如何更改条形图的 colors 而不影响变量的图例标签?

Pointing out to great suggestion from @Dave2e you can try this (Data used from similar questions you posted):指出@Dave2e 的好建议,您可以试试这个(数据来自您发布的类似问题):

df %>% 
  left_join(my_se) %>% 
  mutate(zone = factor(zone,labels = c("x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11"))) %>% 
  ggplot(aes(x=zone, y=meangpp, fill = groups)) + 
  geom_col(position = position_dodge()) +
  geom_errorbar(aes(x=zone, ymin=meangpp-se, ymax=meangpp+se), width=0.4, position = position_dodge(.9)) +
  ggtitle("using standard error")+
  scale_fill_manual(labels = c("GC", "IP", "MR","CS"),values=cbPalette)+
  labs(y= 'an', x = "Land Cover")+theme_bw()+theme(legend.title =element_blank())+
  theme(legend.text=element_text(size=11),axis.text.y=element_text(size=11.5),
        axis.text.x=element_text(size=11.5),axis.title.x = element_text(size = 12), axis.title.y = element_text(size = 12))

在此处输入图像描述

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

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