0

我试图在 x 轴上绘制一条线,它基本上是一堆零和一。1 为绿色,0 为红色。当我尝试这样做时, ggplot 的 color_scale_gradient 基本上是在线顶部的颜色。

看起来像这样

错误的情节

线条的颜色应如下所示:

所需的情节

colorbar 是一个由 0 和 1 组成的向量。

p <- ggplot(data1,aes(newx,newy, group = 1, colour=newy))+
    geom_line(size=1.5, show.legend = FALSE)+
    scale_colour_gradient(low="red2", high="green3") + 
    geom_line(data = colorFrame, aes(as.numeric(x)-5,as.numeric(ys), color = colorbar),size=3, show.legend = FALSE)+
    xlim(0,1300)

p <- p + 
    theme(panel.background = element_blank(), axis.ticks.x = element_blank(),  
      axis.text.x = element_blank(), axis.line.y = element_line(colour = 'black'), 
      axis.ticks.y.left = element_line(colour = 'black')) + 
   scale_y_continuous(breaks = seq(0, 12, 1), limits = c(-1, 12), expand = c(0,0))   
4

1 回答 1

0

一种解决方案是创建两个子图并将它们缝合在一起。我在这里使用cowplottheme_void,但实际上下面的第二个图可以看起来像你想要的那样。

p1 <- ggplot(df, aes(x,y, group = 1, colour=y)) +
  geom_line(size=1.5, show.legend = FALSE) +
  scale_colour_gradient(low="red2", high="green3") +
  theme(panel.background = element_blank(), 
        axis.ticks.x = element_blank(),  
        axis.text.x = element_blank(), 
        axis.line.y = element_line(colour = 'black'), 
        axis.ticks.y.left = element_line(colour = 'black')) + 
  scale_y_continuous(breaks = seq(0, 12, 1), limits = c(-1, 12), expand = c(0,0)) +
  labs(x = NULL)

p2 <- ggplot(df, aes(x, y = 0, colour=z)) +
  geom_line(size=1.5, show.legend = FALSE) +
  scale_colour_gradient(low="red2", high="green3") +
  theme_void()

cowplot::plot_grid(p1, p2, 
                   ncol = 1, 
                   rel_heights = c(1, .05),
                   align = 'v')

在此处输入图像描述


数据

df <- data.frame(x = 1:50, 
                 y = runif(50, 0, 12), 
                 z = sample(c(0,1), 50, replace = TRUE))
于 2020-10-07T01:56:00.417 回答