0

I have four separate datasets which all have the same x-axis:

x        y1    y2    y3    y4
12350  0.032  0.283 0.043  0.012
13200  0.234  0.229 0.934  0.002
15504  0.001  0.510 0.394. 0.294
17709  0.923  0.394 0.022  0.202

How do I enter this in ggplot? I can plot individual plots, but i'm not sure how to combine them. Adding the two plots below does not work:

ggplot(df, aes(x=x, y=y1)) + geom_line()
ggplot(df, aes(x=x, y=y2)) + geom_line()

CCZ23
  • 151
  • 12

2 Answers2

0

Sounds like you want a plot with four curves. You can transform the data frame from wide to long using any number of transformation functions. Basically you want to end up with a data frame with three columns, one for the x values, one for the y values, and one with an identifier showing which of the original y's is associated with each x,y pair.

x     y     id
12350 0.032 y1
12350 0.028 y2
12350 0.043 y3
12350 0.012 y2
13200 0.234 y1
etc.

Then use the id group aesthetic to plot the curves individually. If you do a search on "wide to long" you'll get lots of suggestions for exactly how to make the transformation.

Fleetboat
  • 189
  • 7
0

Using the data.table package (use install.packages('data.table') if you don't have the package installed) this could be done like so:

library(data.table)
library(ggplot2)

data_long <- melt(data, id.vars = 'x')

ggplot(data_long, aes(x = x, y = value, color = variable)) +
   geom_line()

melt will automatically generate the columns variable (containing the names of what where your columns y1-y4) and value (containing, you guessed it, the values).

o_v
  • 112
  • 8