1

I am kind of beginner in ggplot2. I have this dataframe:

df <- data.frame(testno = 1:4, y1 = c(1.2,3.1,4.6,6.7), y2 = c(5,3.2,9.6,8.8))
df$testno <- factor(df$testno)

from which I can easily plot:

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

simple scatter plot x,y

I melt the dataframe (either because I need to do it, or because what I receive to analyze is actually already molten)"

dfmelt <- melt(df, id = "testno")

Can ggplot with geom_point be applied to the molten dataframe in order to obtain the scatterplot above? For instance, this way does not work.

ggplot(dfmelt) +  geom_point(aes(x=value, y=value, group = testno))

Of course, the dataframes I work with are much larger/longer and it would be very convenient to keep the molten dataframe without using dcast or similar approach to get to wide-format. I could not find the proper keyword to find an answer to this simple issue.

Thanks for your help!

Community
  • 1
  • 1
Alex.z
  • 15
  • 3

1 Answers1

0

It is good practice to feed tidy data into ggplot where each observation is on one row and each variable is in a column. That is clearly not the case for your meltdf dataframe. Luckily it is easy to make the data tidy again (even for bigger dataframes) if you want to plot them:

recreated_df <- spread(dfmelt, key = variable, value = value)

> recreated_df
      testno  y1  y2
1      1 1.2 5.0
2      2 3.1 3.2
3      3 4.6 9.6
4      4 6.7 8.8

For other purposes you can of course keep your melted dataframe.

apitsch
  • 1,532
  • 14
  • 31