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

时间:2019-04-05 07:25:09

标签: r ggplot2 colors gradient linear-gradients

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

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

第二,可以在图表上方显示“我”文本吗?当它位于图表顶部时,很难阅读

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")

1 个答案:

答案 0 :(得分:3)

要在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