r - 如何根据条件为变量添加颜色
问题描述
图书馆(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))
如何根据条件更改变量的颜色
预期产出
我的输出
解决方案
使用 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))
推荐阅读
- groovy - 如何将变量限制为特定的允许值?
- python - Python在两个引号之间查找特定单词前面的行
- teamcity - 如何使用两个 % 符号在团队城市中配置参数值
- scala - scala如何使用val而不是var
- haskell - 在 Haskell 中执行多个命令的基本问题
- python - 为什么比较具有相同值的两个字符串会导致错误结果?
- python - __init__ 没有 self 参数的函数定义
- javascript - 当我们在javascript中有多个具有相同ID的表单时选择表单的信息
- python - 生成几何分布时的类型错误(python 3)
- pandas - 如何将系列列表转换为两列数据框?