gpt4 book ai didi

r - 如何在ggplot2中获得水平颜色渐变?

转载 作者:行者123 更新时间:2023-12-02 20:02:22 25 4
gpt4 key购买 nike

我想创建一个水平温度计图表,颜色渐变从绿色(左)到红色(右)。

我能够添加颜色渐变,但它是垂直的而不是水平的。

其次,是否可以在图表上方显示“我”文本?当它位于图表顶部时很难阅读

library(ggplot2)
library(grid)

g <- rasterGrob(c("lightgreen", "yellow", "orange", "red"),
width=unit(1,"npc"), height = unit(1,"npc"),
interpolate = TRUE)

myVariable1 <- 17
dataset <- data.frame(myVariable1)

maxVariable1 = max(myVariable1, 25)

ggplot(dataset, aes(myVariable1)) +
scale_x_continuous(expand = c(0, 0), limits = c(0, maxVariable1)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, 10)) +

annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +

theme(
axis.title.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank()
) +
geom_vline(aes(xintercept=myVariable1), color="red", size=1) +
annotate("text", x=myVariable1-1, y=10-0.4, label="Me", colour="red")

最佳答案

要在 rasterGrob 对象中获取水平渐变,您应该像这样定义图像:

> matrix(c("lightgreen","yellow","orange","red"), nrow = 1)
[,1] [,2] [,3] [,4]
[1,] "lightgreen" "yellow" "orange" "red"

而不是这个:

> c("lightgreen","yellow","orange","red")
[1] "lightgreen" "yellow" "orange" "red"

或者这个:

> matrix(c("lightgreen","yellow","orange","red"), ncol = 1)
[,1]
[1,] "lightgreen"
[2,] "yellow"
[3,] "orange"
[4,] "red"

对于图表区域之外的标签,如果您在笛卡尔坐标中关闭裁剪,则可以做到这一点:

# define raster grob with horizontal gradient
g <- rasterGrob(matrix(c("lightgreen","yellow","orange","red"), nrow = 1),
width=unit(1,"npc"), height = unit(1,"npc"),
interpolate = TRUE)

ggplot(dataset, aes(myVariable1)) +
scale_x_continuous(expand = c(0, 0), limits = c(0, maxVariable1)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, 10)) +
annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_vline(aes(xintercept=myVariable1), color="red", size=1) +

# no need to adjust y value; we can use the maximum limit set above,
# & assign a negative number to vjust instead;
# also, since it's now sitting atop the chart, it'll make more sense
# to align the label with myVariable, rather than dodge it to one side.
annotate("text", x=myVariable1, y=10, label="Me", colour="red",
vjust = -0.5) +

# turn off clipping here
coord_cartesian(clip = "off") +

# add plot.margin specification to theme, with large value for top margin
# (5.5 is the default for all four sides)
theme(
axis.title.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank(),
plot.margin = unit(c(20, 5.5, 5.5, 5.5), "pt")
)

enter image description here

关于r - 如何在ggplot2中获得水平颜色渐变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55530239/

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