1

I want to combine three data frames with different row numbers and same column names into the same plot. Below is the code I am using based on another stack overflow question >ggplot combining two plots from different data.frames<

    df1 <- data.frame(dist=c(5,10,15,25,30,40,45,50), #8
                      r2=c(105,90,70,50,40,15,17,8))
    df2 <- data.frame(dist=c(5,10,15,25,30,40,45,50,55,60),#10
                      r2=c(100,80,60,40,30,25,15,10,5,3))
    df3 <- data.frame(dist=c(3,5,10,15,20,25,30,35,40,45,50,60),#12
                      r2=c(110,100,80,60,50,35,30,25,20,15,10,5))
      ggplot() +
      theme_bw() +
      geom_line(data = df1, aes(x = dist, y = r2), color = "red") +
      geom_line(data = df2, aes(x = dist, y = r2), color = "blue")+
      geom_line(data = df3, aes(x = dist, y = r2), color = "orange")

However, in those answers, there is not information about adding legends, title or adjusting axis.
Any advice to include information from those three data frames into the plot is highly appreciated.

Javier_HV
  • 15
  • 3

1 Answers1

1

ggplot2 really likes things in a "long" format, so let's combine the data, preserving the frame name in a sense. While I'm using "df1" the string to add to df1 the frame, you can change the strings to whatever you want. Also arbitrary is the "nm" label, this might be more descriptive (but you need to be consistent with it in aes).

library(dplyr)
library(ggplot2)

df1$nm <- "df1"
df2$nm <- "df2"
df3$nm <- "df3"

bind_rows(df1, df2, df3) %>% 
  ggplot(aes(dist, r2)) +
  theme_bw() +
  geom_line(aes(color = nm)) +
  scale_color_manual(values = c(df1 = "red", df2 = "blue", df3 = "orange"))

ggplot

Also, you can add the color aesthetic mapping to the original ggplot call, there's nothing special with adding it here. I just reduced your code to deal with this format of data.

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • Thanks for your answer. But I could not figure out how to change colors for each data frame and at the same time showing legend. Each df is a population with previous defined colors (i.e df1 -> "orange", df2 -> "black", df3 -> "pink") . Thanks. – Javier_HV Apr 06 '20 at 19:17
  • `scale_color_manual` lets you control the color for each group. – r2evans Apr 06 '20 at 20:24