使用ggplot绘制多条线,颜色由y值决定。

huangapple go评论61阅读模式
英文:

ggplot multiple lines colored by y-value

问题

我想生成一个类似于这张图片的图表,但数据点上的符号要更大,颜色根据它们的y轴数值而变化:
[![在此输入图片描述][1]][1]

这是我尝试过的代码的一个 '最小示例':

    library(ggplot2)
    strtT <- Sys.time()-30*(24*3600);
    endT <- Sys.time()-24*3600
    xAxis <- seq(from=strtT,to=endT,by=24*3600)
    
    dat <- data.frame(x = xAxis, 
                      y1 = rnorm(length(xAxis),mean=40,sd=30),
                      lab = "Y1")
    fulldat <- dat;
    dat <- data.frame(x = xAxis, 
                      y1 = rnorm(length(xAxis),mean=15,sd=5),
                      lab = "Y2")
    fulldat <- rbind(fulldat,dat);
    dat <- data.frame(x = xAxis, 
                      y1 = rnorm(length(xAxis),mean=80,sd=10),
                      lab = "Y3")
    fulldat <- rbind(fulldat,dat);
    
    gp<-ggplot(fulldat, aes(x,y1,color=y1)) + 
      # geom_point(aes(shape=(factor(lab)),size=6),show.legend=FALSE) +
      geom_point(aes(shape=(factor(lab)),size=6)) +
      # geom_line(aes(x,y1,linewidth=1.5,color=(14+as.numeric(factor(lab))))) +
      geom_line(aes(group=factor(lab)),linewidth=1.0) +
      scale_color_gradientn(colours=c("blue","gray80","red"), limits=c(0,max(dat$y1)),
                            breaks=c(15,30,45,60,75,90,110), 
                            labels=c(1,2,3,4,5,6,7), 
                            na.value = "green",
                            guide=guide_colorbar(nbin=10, raster=F, barwidth=2, frame.colour=c("black"),
                                                 frame.linewidth=1, ticks.colour="black")) +
      theme(legend.position = "right") 
    gp

最大的问题是我无法弄清楚如何让线条的颜色由变量 "lab" 决定,而将Y1数据作为数据点,颜色根据其y轴数值而变化。在这个例子中,数据点和线条都根据y轴数值着色。似乎无法将这两者分开。

另一个问题是改进图例的外观。颜色条应该是全高度的,线型的图例(lab变量)应该在颜色条旁边,而不是在下方。那个说着 "size" 的图例条目上有一个实心点和 '6' 是什么?我能把它去掉吗?
英文:

I want to produce a graph that looks something like this image, but larger symbols on the data points, colored by their y-axis value:
使用ggplot绘制多条线,颜色由y值决定。

Here is a 'minimal example' using the code I have tried:

library(ggplot2)
strtT &lt;- Sys.time()-30*(24*3600);
endT &lt;- Sys.time()-24*3600
xAxis &lt;- seq(from=strtT,to=endT,by=24*3600)


dat &lt;- data.frame(x = xAxis, 
                  y1 = rnorm(length(xAxis),mean=40,sd=30),
                  lab = &quot;Y1&quot;)
fulldat &lt;- dat;
dat &lt;- data.frame(x = xAxis, 
                  y1 = rnorm(length(xAxis),mean=15,sd=5),
                  lab = &quot;Y2&quot;)
fulldat &lt;- rbind(fulldat,dat);
dat &lt;- data.frame(x = xAxis, 
                  y1 = rnorm(length(xAxis),mean=80,sd=10),
                  lab = &quot;Y3&quot;)
fulldat &lt;- rbind(fulldat,dat);

gp&lt;-ggplot(fulldat, aes(x,y1,color=y1)) + 
  # geom_point(aes(shape=(factor(lab)),size=6),show.legend=FALSE) +
  geom_point(aes(shape=(factor(lab)),size=6)) +
  # geom_line(aes(x,y1,linewidth=1.5,color=(14+as.numeric(factor(lab))))) +
  geom_line(aes(group=factor(lab)),linewidth=1.0) +
  scale_color_gradientn(colours=c(&quot;blue&quot;,&quot;gray80&quot;,&quot;red&quot;), limits=c(0,max(dat$y1)),
                        breaks=c(15,30,45,60,75,90,110), 
                        labels=c(1,2,3,4,5,6,7), 
                        na.value = &quot;green&quot;,
                        guide=guide_colorbar(nbin=10, raster=F, barwidth=2, frame.colour=c(&quot;black&quot;),
                                             frame.linewidth=1, ticks.colour=&quot;black&quot;)) +
  theme(legend.position = &quot;right&quot;) 
gp

The biggest issue I cant work out is that I want the lines to be colored by the variable "lab", and the Y1 data as data points, colored by their y-axis value. In this example, both the data points and lines are colored by the y-axis value. It seems one cant separate the two.

Additional issue is to improve the looksof the legend. Color bar should be full height, and the legend for the line styles (lab variable) to be beside the color bar, not below. And what is that legend entry that says size with a solid point and '6'?? Can I get rid of that?

答案1

得分: 1

通常在`ggplot2`中,每个美学属性(aesthetic)对应一个比例尺,也就是说你只能有一个`color`比例尺。克服这个问题的一个选项是使用`ggnewscale`包,它允许每个美学属性拥有多个比例尺。因此,在`geom_point`中将`y1`映射到`color`,然后为`y1`添加`scale_color_gradientn`。然后通过`ggnewscale::new_scale_color()`添加一个新的颜色比例尺,并添加你的线条以及你想要的颜色(在示例代码中,我通过`scale_color_brewer`添加了一个调色板):

```R
library(ggplot2)
library(ggnewscale)

ggplot(fulldat, aes(x, y1)) +
  geom_point(aes(shape = lab, color = y1), size = 6) +
  scale_color_gradientn(
    colours = c("blue", "gray80", "red"), limits = c(0, max(dat$y1)),
    breaks = c(15, 30, 45, 60, 75, 90, 110),
    labels = c(1, 2, 3, 4, 5, 6, 7),
    na.value = "green",
    guide = guide_colorbar(
      nbin = 10, raster = F, barwidth = 2, frame.colour = c("black"),
      frame.linewidth = 1, ticks.colour = "black"
    )
  ) +
  ggnewscale::new_scale_color() +
  geom_line(aes(group = lab, color = lab), linewidth = 1.0) +
  scale_color_brewer(palette = "Set1") +
  theme(legend.position = "right")

使用ggplot绘制多条线,颜色由y值决定。


<details>
<summary>英文:</summary>

In general in `ggplot2` there is one scale per aesthetic, i.e. you can only have one `color` scale. One option to overcome this would be to use the `ggnewscale` package which allows to have multiple scales per aesthetic. Hence, map `y1` on `color` in `geom_point`, then add the `scale_color_gradientn` for `y1`. Afterwards add a new color scale via `ggnewscale::new_scale_color()` and add your lines plus your desired colors (in the example code I added a brewer pal via `scale_color_brewer`:

library(ggplot2)
library(ggnewscale)

ggplot(fulldat, aes(x, y1)) +
geom_point(aes(shape = lab, color = y1), size = 6) +
scale_color_gradientn(
colours = c("blue", "gray80", "red"), limits = c(0, max(dat$y1)),
breaks = c(15, 30, 45, 60, 75, 90, 110),
labels = c(1, 2, 3, 4, 5, 6, 7),
na.value = "green",
guide = guide_colorbar(
nbin = 10, raster = F, barwidth = 2, frame.colour = c("black"),
frame.linewidth = 1, ticks.colour = "black"
)
) +
ggnewscale::new_scale_color() +
geom_line(aes(group = lab, color = lab), linewidth = 1.0) +
scale_color_brewer(palette = "Set1") +
theme(legend.position = "right")



[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/UcAXO.png

</details>



huangapple
  • 本文由 发表于 2023年4月7日 02:13:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952551.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定