gpt4 book ai didi

r - ggplot 动态更改 x 轴标签颜色

转载 作者:行者123 更新时间:2023-12-05 03:55:56 25 4
gpt4 key购买 nike

下面是测试代码:

library(tidyverse)

df<- data.frame(PCP = c("BOB","FRED","ED","Other"),
closed = c(42,64,45,1812),
total= c(53,81,58,3188),
percentage = c(.7924,.7901,.7758,.5683),
row= c(1, 2, 3,4),
color =c("0099FF","#CCCCCC","#CCCCCC","#660033"),
color_fill = c("99","0","0","98"
))

col <- c(
"99" = "#0099FF",
"98" = "#660033",
"0" = "#CCCCCC"
)

df %>%
arrange(desc(percentage)) %>%
mutate(PCP = PCP,
closed = closed,
total = total,
percentage = percentage,
row = row,
color = color,
color_fill = color_fill) -> df1

ggplot(df1,aes(x=PCP, y = percentage,fill=color_fill, color = color)) +
geom_col() +
coord_flip() +
labs(x ="PCP Name",
y = "Percentage of Gap Closures",
title = "TOP 10 PCPs")+
scale_fill_manual(values = col)+
scale_color_manual(values = col) +
scale_y_continuous(labels = percent_format(), limits=c(0,1))+
theme(legend.position = "none",
panel.grid = element_blank(),
panel.background = element_blank(),
text = element_text(size=15),
plot.caption = element_text(hjust = 0, face= "italic"),
axis.text.y = element_text(colour = col ))

我的目标是将 x 轴标签与条形颜色相匹配。

我尝试过解决方案, Matching axis.text labels to colors contained in data frame variable in ggplot

但是,在尝试因子水平部分时,我收到错误消息,因为我的实际数据包含使用相同#CCCCCC 颜色代码的其他值。

下面是附加代码的输出。

Results

我做错了什么吗?

最佳答案

我不完全确定这里的问题是什么(我的意思是我知道你以错误的顺序提供了颜色;在主题中你必须使用 col[as.integer(df$color) ] 来模仿因子的顺序,但我不知道为什么)但我有一个很好的解决方法。

ggplot2 中一个鲜为人知的函数是 ggplot_build。顾名思义,您可以使用它来构建绘图,这意味着您可以从中提取所需的值。基于此我写了一个小函数可以做你想做的事。

axis_text_color <- function(plot, col = "fill") {
c <- ggplot_build(plot)$data[[1]]
plot +
theme(axis.text.y = element_text(colour = c[[col]]))
}

您使用它的方式是首先将绘图保存在一个对象中:

library(tidyverse)
plot <- ggplot(df, aes(
x = PCP,
y = percentage,
fill = color_fill,
color = color
)) +
geom_col() +
coord_flip() +
labs(x = "PCP Name",
y = "Percentage of Gap Closures",
title = "TOP 10 PCPs") +
scale_fill_manual(values = col) +
scale_color_manual(values = col) +
scale_y_continuous(labels = scales::percent_format(), limits = c(0, 1)) +
theme(
legend.position = "none",
panel.grid = element_blank(),
panel.background = element_blank(),
text = element_text(size = 15),
plot.caption = element_text(hjust = 0, face = "italic")
)

然后在该图上调用函数:

axis_text_color(plot)

reprex package 创建于 2020-01-20 (v0.3.0)

关于r - ggplot 动态更改 x 轴标签颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59826366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com