首页 > 解决方案 > 如何根据条件为变量添加颜色

问题描述

图书馆(ggplot2)

ggplot(dealflow_summary_fiscal_yr,aes(x=Total,y=Type,fill=factor(status, c("Open", "Closed"))))+
  geom_bar(stat='identity',width=0.2)+
  geom_text(aes(label = after_stat(x)),
            stat = "summary",fun.data = function(x){data.frame(y = sum(x))}, 
            hjust= 0, position = position_stack(0),colur=ifelse(dealflow_summary_fiscal_yr$status=="Closed","#FFFFFF","#000000"))+
  geom_text(aes(label = after_stat(x), group = Type),
            stat = "summary",fun.data = function(x){data.frame(y = sum(x))}, 
            hjust= 0, position = position_stack(1))+
  labs(x="", y="", fill="")+
  scale_fill_manual(values=c("#284a8d", "#00B5CE"), 
                    limits = c("Closed", "Open")) +
  theme_classic() +
  theme(axis.line.y = element_blank(),
        axis.ticks = element_blank(),
        legend.position = "bottom",
        axis.text.x = element_text(face = "bold", color = "black", 
                                   size = 10, angle = 45, hjust = 1))

如何根据条件更改变量的颜色

预期产出

我的输出

标签: rggplot2

解决方案


使用 teunbrand 评论中提到的问题中的数据:

  x %>%
  mutate(status = factor(status, levels = c("Open", "Closed"))) %>%
  group_by(Type, status) %>%
  summarise(n = sum(Total)) %>%
  add_count(Type, wt = n, name = "total") %>%
  ggplot(aes(n, Type)) +
  geom_col(aes(fill = status)) +
  geom_text(
    aes(label = n, color = status), 
    position = ggplot2::position_stack(vjust = 0.5),
    show.legend = FALSE,
    fontface = "bold"
  ) +
  geom_text(aes(label = total, x = total), hjust = -0.1) +
  scale_fill_manual(NULL, values = c(Closed = "#284a8d", Open = "#00B5CE")) +
  scale_color_manual(NULL, values = c(Closed = "white", Open = "black")) +
  scale_x_continuous(expand = c(0,0), limits = c(0, 650)) +
  theme_classic() +
  labs(x = NULL, y = NULL) +
  theme(
    legend.position = "bottom",
    axis.ticks = element_blank()
  ) +
  guides(fill = guide_legend(reverse = TRUE))

在此处输入图像描述


推荐阅读