user1728853
user1728853

Reputation: 2707

Reshape/melt a dataframe for scatter plot

I have a data file that looks like this:

x   ys --------------------->
1   20   25   30   12   22   12
2   12    9   12   32   12 
3   33   12   11    6    1
4    5   10   41   12    3
5    7   81   12   31    8   3   4   11

I'd like to make a scatter plot with one x value and multiple y values (ys). I was trying to use reshape with melt, but I couldn't get the proper data structure created to make this plot. How can I do this in R and plot with ggplot? Thanks for the help.

Upvotes: 1

Views: 4119

Answers (2)

BenBarnes
BenBarnes

Reputation: 19454

You can use the matplot function.

Assuming your data is in an object called myDat and that the x values are in column 1 and the y values are in the other columns,

matplot(x = myDat[, 1], y = myDat[, -1], type = "p", pch = 21)

would produce something like

enter image description here

Or using the latticeExtra package for the ggplot2like theme:

library(latticeExtra)

xyplot(as.formula(paste(paste0(names(myDat)[-1], collapse = "+"), "~",
  names(myDat[1]))),
  data = myDat, par.settings = ggplot2like(), grid = TRUE)

enter image description here

Upvotes: 0

Beasterfield
Beasterfield

Reputation: 7123

So what did not work with melt? And what Problems did you have with geom_point()? Hard to say if this is what you want:

library( "reshape2" )
library( "ggplot2" )

df <- data.frame( x = rnorm(20), ya = rnorm(20), yb = rnorm(20), yc = rnorm(20) )
df <- melt(df, id.vars="x", variable.name="class", value.name="y")

ggplot( df, aes( x = x, y = y) ) +
  geom_point( aes(colour = class) )

ggplot( df, aes( x = x, y = y) ) +
  geom_point() +
  facet_wrap( "class" )

Upvotes: 3

Related Questions