Home > database >  How to plot two lines (group of rows) in the same plot
How to plot two lines (group of rows) in the same plot

Time:07-18

I Have data of 80 line and 210 columns.

Here i plot one line

ggplot(data=Data[c(1:5),], aes(x=x_lab, y=col1, group=1))  
  geom_line() 
  geom_point()   ggtitle("plot of col1 ")

enter image description here

Can you tell me please how i can plot also the rows from 6 to 10 of col1 in other line (like i did for rows 1:5) and in other color Thank you

CodePudding user response:

While with smaller datasets it's tempting to do geom_line(data=...) for each separate line, this scales poorly. Since ggplot2 benefits from having its data in a "long" format, I suggest you reshape it (reshape2::melt or tidyr::pivot_longer) and then plot.

Lacking your data, I think these will work:

library(ggplot2)

### pick one of these two
longData <- tidyr::pivot_longer(Data, -x_lab, names_to = "variable", values_to = "y")
longData <- reshape2::melt(Data, "x_lab", variable.name = "variable", value.name = "y")

### plot all at once
ggplot(longData, aes(x_lab, y = y, group = variable))  
  geom_line()   geom_point()

(I find it often useful to use group=variable, color=variable for more breakout of the lines.)

CodePudding user response:

A quick and easy solution would be to add a grouping variable directly to your data if you are only hoping to plot these 10 lines.

Data$group <- rep("group1", "group2", each =5)
ggplot(Data, aes(x,y))  
geom_line(aes(color = group))
  • Related