[英]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.