繁体   English   中英

如何在 ggplot2 中绘制 x 轴值略有不同的多条线

[英]How to draw multiple lines with slightly different x-axis values in ggplot2

我想用 2 行创建一个 ggplot2。 两条线的 x,y 值不同。 我已经用常规行 plot 做到了这一点

plot(d$ball,d$total,col="blue",type="l",lwd=2,xlab="Overs",ylab='Runs',
     main="Worm chart of match")
lines(d1$ball,d1$total,type="l",col="red",lwd=2)
teams <-c(t1,t2)
legend(x="topleft",legend=teams,
       col=c("blue","red"),bty="n",cex=0.8,lty=1,lwd=2)

我发现的大多数 ggplot2 示例都假设 x 值(通常是日期)与不同的 y 值相同。 我怎样才能做到这一点?

Test data
---------
x   k   y
3.1 1   15
3.2 0   15
3.3 0   15
3.4 0   15
3.5 1   16
3.6 0   16
3.7 1   17
3.8 4   21
4.1 4   21

 x1 m   y1
2.6 4   15
3.1 0   15
3.2 1   16
3.3 0   16
3.4 4   20
3.5 0   20
3.6 4   24
3.7 0   24
4.1 0   24
4.2 1   25

我需要 plot x,y 和 x1,y1 在单个 plot 中。 行数会有所不同,x,x1 值也可能略有不同

如果您不想合并您的 dfs 并以整洁的方式重塑它们,这里有一个想法:

library(ggplot2)

ggplot() +
  geom_line(data = df1, aes(x = x, y = y, color = "1")) +
  geom_line(data = df2, aes(x = x1, y = y1, color = "2")) +
  scale_color_manual(name = "Lines",
                     values = c("1" = "blue", "2" = "red"))

代表 package (v2.0.0) 于 2021 年 5 月 20 日创建

数据:

df1 <- structure(list(x = c(3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 
                            4.1), k = c(1L, 0L, 0L, 0L, 1L, 0L, 1L, 4L, 4L), y = c(15L, 15L, 
                                                                                   15L, 15L, 16L, 16L, 17L, 21L, 21L)), class = "data.frame", row.names = c(NA, 
                                                                                                                                                            -9L))
df2 <- structure(list(x1 = c(2.6, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 
                             4.1, 4.2), m = c(4L, 0L, 1L, 0L, 4L, 0L, 4L, 0L, 0L, 1L), y1 = c(15L, 
                                                                                              15L, 16L, 16L, 20L, 20L, 24L, 24L, 24L, 25L)), class = "data.frame", row.names = c(NA, 
                                                                                                                                                                                 -10L))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM