R中条形图中变量特征的固定颜色

埃德温

我有一个数据框,我想为其可视化不同的东西。在每个条形图中,变量/属性的相同特征应该具有相同的颜色。例如:

data_mtcars <- mtcars

  data <- data_mtcars %>%                
    group_by(am, gear) %>%
    summarise(Freq = sum(mpg)) %>%
    group_by(am) %>%
    mutate(Prop = Freq / sum(Freq)) %>% 
    arrange(desc(Prop))

第一个图具有变量“齿轮”的三个特征。

ggplot(data) +
  aes(x = am, y = Prop, fill = reorder(gear, Prop), width=0.5) +
  geom_col() + scale_y_continuous(labels = function(x) paste0(eval(x*100), "%")) +
  geom_text(aes(label = if_else(Prop>0.05, scales::percent(Prop),NULL)), position = position_stack(0.4))+    
  theme_minimal() +
  theme(legend.title = element_blank()) + ylab("") + xlab("") +
  scale_fill_brewer(palette = "Set3")

这给了我可变齿轮特征“3”的紫色。如果我改变特征的数量,颜色不应该改变。

df <- data[data$gear!=4,]

ggplot(df) +
  aes(x = am, y = Prop, fill = reorder(gear, Prop), width=0.5) +
  geom_col() + scale_y_continuous(labels = function(x) paste0(eval(x*100), "%")) +
  # scale_x_date(breaks = unique(df_sum_EAD$Stichtag) , date_labels = "%d.%m.%Y") +
  geom_text(aes(label = if_else(Prop>0.05, scales::percent(Prop),NULL)), position = position_stack(0.4)) + theme_minimal() +
  theme(legend.title = element_blank()) + ylab("") + xlab("")+ scale_fill_brewer(palette = "Set3")

现在相同的特征有不同的颜色(特征“3”是黄色)。如何解决这个问题。我试图修复因子变量的水平,但我不知道如何在绘图中包含适当的参数。

data_mtcars$gear <- factor(data_mtcars$gear, levels=levels(as.factor(data_mtcars$gear)), ordered=T)
斯蒂芬

要为类别获得一致的颜色,您可以使用命名颜色向量,然后可以使用它scale_color/fill_manual来始终为每个类别设置相同的颜色:

library(dplyr)
library(ggplot2)

data_mtcars <- mtcars

data <- data_mtcars %>%                
  group_by(am, gear) %>%
  summarise(Freq = sum(mpg)) %>%
  group_by(am) %>%
  mutate(Prop = Freq / sum(Freq)) %>% 
  arrange(desc(Prop))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)

data <- mutate(data, gear = reorder(gear, Prop))

# Named vector of colors
colors_gear <- scales::brewer_pal(palette = "Set2")(length(levels(data$gear)))
colors_gear <- setNames(colors_gear, levels(data$gear))

make_plot <- function(d) {
  ggplot(d) +
    aes(x = am, y = Prop, fill = reorder(gear, Prop), width=0.5) +
    geom_col() + scale_y_continuous(labels = function(x) paste0(eval(x*100), "%")) +
    geom_text(aes(label = if_else(Prop>0.05, scales::percent(Prop),NULL)), position = position_stack(0.4)) + theme_minimal() +
    theme(legend.title = element_blank()) + ylab("") + xlab("")+ 
    scale_fill_manual(values = colors_gear)
}

make_plot(data)

make_plot(data[data$gear!=4,])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章