Reda
Reda

Reputation: 497

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

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

Upvotes: 0

Views: 127

Answers (2)

r2evans
r2evans

Reputation: 160417

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 visual breakout of the lines.)

Upvotes: 1

mrw15031
mrw15031

Reputation: 11

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))

Upvotes: 0

Related Questions