gpt4 book ai didi

r - geom_bar 的渐变填充相对于每个条进行缩放并且未映射到变量

转载 作者:行者123 更新时间:2023-12-04 00:49:44 27 4
gpt4 key购买 nike

我的目标是重现这个图,我的问题是重现每个条中的渐变填充。

评论后添加
@PavoDive 的好评将我们引导至 a question这基本上是说“你不能用 ggplot2 做到这一点,而且即使你能做到,这也是一个坏主意。”同意这是一个糟糕的图形选择,但出于教学目的,我想重新创建原始版本,然后显示改进。那么,是否有编程解决方案?

enter image description here

使用 ggplot 后面的数据代码我已经接近了,除了每个条形(和微小的刻度线)都相同的一致渐变着色。但是我的努力导致填充的条形与 y 值匹配,而在原始图中,每个条形都填充了相同的模式。我如何达到这种效果?

ggplot(df, aes(x = x, y = y, fill = y)) +
geom_hline(yintercept = seq(0, .35, .05), color = "grey30", size = 0.5, linetype = "solid") +
geom_bar(stat = "identity", width = 0.4) +
scale_fill_gradient(low='green4', high='green1', guide = FALSE) +
theme(legend.position = "none") +
theme_minimal() +
geom_text(data = df, aes(label = scales::percent(y), vjust = -.5)) +
theme(axis.text.y = element_blank()) +
theme(axis.ticks = element_blank()) +
labs(y = "", x = "") +
ggtitle("Question 15: Do you feel prepared to comply with the upcoming December
2015 updated requirements of the FRCP that relate to ediscovery") +
theme(plot.title = element_text(face = "bold", size = 18)) +
theme(panel.border = element_blank())

enter image description here

数据
df <- data.frame(x = c("Prepared", "Somewhat\nprepared", "Not prepared", "Very prepared"),
y = c(.32, .31, .20, .17))
df$x <- factor(df$x, levels = c("Prepared", "Somewhat\nPrepared", "Not Prepared", "Very Prepared"))

最佳答案

这是一个选项,使用 geom_path用缩放 y 来着色而不是条形。这会创建一些新数据( dat ),从 0 到每个 df$y 的序列值(此处为长度 100,在 dat$y 列中)。然后,创建每个序列的缩放版本(从 0 到 1),用作颜色渐变(称为 dat$scaled )。缩放是通过简单地将每个序列除以其最大值来完成的。

## Make the data for geom_path
mat <- mapply(seq, 0, df$y, MoreArgs = list(length=100)) # make sequences 0 to each df$y
dat <- stack(data.frame(lapply(split(mat, col(mat)), function(x) x/tail(x,1)))) # scale each, and reshape
dat$x <- rep(df$x, each=100) # add the x-factors
dat$y <- stack(as.data.frame(mat))[,1] # add the unscaled column
names(dat)[1] <- "scaled" # rename

## Make the plot
ggplot(dat, aes(x, y, color=scaled)) + # use different data
## *** removed some code here ***
geom_hline(yintercept = seq(0, .35, .05), color = "grey30", size = 0.5, linetype = "solid") +
theme(legend.position = "none") +
theme_minimal() +
geom_text(data = df, aes(label = scales::percent(y), vjust = -.5), color="black") +
theme(axis.text.y = element_blank()) +
theme(axis.ticks = element_blank()) +
labs(y = "", x = "") +
ggtitle("Question 15: Do you feel prepared to comply with the upcoming December
2015 updated requirements of the FRCP that relate to ediscovery") +
theme(plot.title = element_text(face = "bold", size = 18)) +
theme(panel.border = element_blank()) +
## *** Added this code ***
geom_path(lwd=20) +
scale_color_continuous(low='green4', high='green1', guide=F)

enter image description here

关于r - geom_bar 的渐变填充相对于每个条进行缩放并且未映射到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31791944/

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