Colour by variable using melted dataframe and facet_wrap

Hello,

I have a dataframe of 60 observations and 13 variables. I am using ggplot to produce plots of all variables against just one variable in the dataframe (in my case its the second column in my dataframe, let's call it df_col2)

I have melted the dataframe and set key variable to be df_col2.

I can produce plots successfully with the following code:

melted_df <- melt(df, id.vars = "df_col2")

ggplot(melted_df, aes(x = "df_col2", y = value))+
geom_point()+
facet_wrap(~variable, scales = "free_y")

Next, I want to colour the points on each plot by a particular variable in another column, in this case the third column in my dataframe.

Is it possible to do this with 1) a melted dataframe, and 2) using facet_wrap?

Any help much appreciated.

For me the following worked:
#include the color column (lets call it "df_colX") into the melt command:
melted_df <- melt(df, id.vars=c("df_col2", "df_colX"))

#then add the color option to the ggplot function:
ggplot(melted_df, aes(x=df_col2, y=value, color=df_colX)) +
geom_point() +
facet_wrap(~variable)

1 Like

Thanks, this works great. Useful to know to identify each variable in the melt() stage.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.