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

R 如何在ggplot2中绘制x轴值稍有不同的多条直线,r,ggplot2,R,Ggplot2,我想创建一个带有两条线的ggplot2。这两条线的x、y值不同。我已经用常规的线图做过了 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"

我想创建一个带有两条线的ggplot2。这两条线的x、y值不同。我已经用常规的线图做过了

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)

我需要在一个图中绘制x,y和x1,y1。行数将不同,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"))

由(v2.0.0)于2021年5月20日创建

数据:


df1您好,您可以使用3列数据框:一列带有行“name”(
line\u name
),一列带有
x
值,一列带有
y
值。然后使用
aes()。es:
ggplot(data=df,aes(x=x,y=y,color=line\u name)+geom\u line()
。如果您需要更多帮助,请提供示例。我想您会在这里找到一些想法:我尝试过合并它们。它会生成NAs。需要看看如何修复。有什么建议吗?您可能喜欢
tidyverse
软件包的强大功能(在这种情况下,尤其是
dplyr
tidyr
)。也许可以看看
full\u join()
pivot\u longer()
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"))
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))