I would like to create a ggplot2 with 2 lines. The x,y values for the 2 lines are different. I have done this with regular line plot as
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)
Most of the ggplot2 examples I found assume that x values(usually date) are same with different y values. How can I do this?
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
I need to plot x,y and x1,y1 in a single plot. The number rows will be different and the x,x1 value also may vary slightly
If you do not want to merge yours dfs and reshape them on a tidy way, here is an idea:
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"))
Created on 2021-05-20 by the reprex package (v2.0.0)
Data:
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.