0

I want to do a scatter (xy) plot of variables in a melted data frame as shown below.

df
class var  mean        
0      x   4.25 
0      y   6.25 
1      x   2.00 
1      y  11.00 

I have tried this, but it plots 4 points. How can plot x and y?

library(ggplot2)

ggplot(df, aes(x=mean, y=mean, group=var, colour=class)) +
geom_point( size=5, shape=21, fill="white")
1
  • 5
    This rare, but your data is in a format that's 'too' long. You need x and y-values on the same row for each observation.
    – Heroka
    Oct 19, 2015 at 11:44

1 Answer 1

3

As Heroka pointed out, you need the data to be in a more wide type format. If the data was read in like this, you may use the following to convert it.

## you don't need this since you already have df
text = "class var mean
0 x 4.25
0 y 6.25
1 x 2.00
1 y 11.00"
df = read.delim(textConnection(text),header=TRUE,strip.white=TRUE,     
stringsAsFactors = FALSE, sep = " ");df2

## use this library to switch from long-wide
library(reshape2)

df2 = dcast(df, class ~ var, value.var = "mean")

library(ggplot2)
ggplot(df2, aes(x=x, y=y, colour=class)) +
  geom_point( size=5, shape=21, fill="white")

enter image description here

1
  • 1
    And I would convert class to factor; the current scale is unnecessary/confusing.
    – Heroka
    Oct 19, 2015 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.