Aanna Aanna - 1 month ago 13
R Question

Best way to build a graph for 3 almost identical graph

I have the following :

person1 = c(1999:2016)
person2 = c(1993:2016)
person3 = c(1950:2016)

namex = data.frame(person1)
namey = data.frame(person2)
namez = data.frame(person3)

rm(person1, person2, person3)

library(plyr)
namex = rename(namex, c("person1"="year"))
namey = rename(namey, c("person2"="year"))
namez = rename(namez, c("person3"="year"))

namex$count = sample(1:80, 18)
namey$count = sample(1:80, 24)
namez$count = sample(1:80, 67)

par(mfrow=c(3,1))
plot(namex, main="namex", xlab="Year", ylab="Count")
plot(namey, main="namey", xlab="Year", ylab="Count")
plot(namez, main="namez", xlab="Year", ylab="Count")


I had a ggplot in mind with 3 dataframes and xlab="Year", ylab="Count" and a legend on the side, but I can't get it to work.

What is the best method to make one graph / plot with the three dataframes?
Any examples?

Answer

This is one of the many possible way, by creating one data frame.

            library(ggplot2)
            person1 = c(1999:2016)
            person2 = c(1993:2016)
            person3 = c(1950:2016)

            namex = data.frame(person1)
            namey = data.frame(person2)
            namez = data.frame(person3)

            rm(person1, person2, person3)

            library(plyr)
            namex = rename(namex, c("person1"="year"))
            namey = rename(namey, c("person2"="year"))
            namez = rename(namez, c("person3"="year"))              

            namex$count = sample(1:80, 18)
            namex$id = "person1"
            namey$count = sample(1:80, 24)
            namey$id = "person2"
            namez$count = sample(1:80, 67)
            namez$id = "person3"

            namesDf <- rbind(namex, namey)
            namesDf <- rbind(namesDf, namez)
            namesDf$id <- as.factor(namesDf$id)

            ggplot(data = namesDf, aes(x = year, y = count)) + 
                    geom_point() +
                    xlab("Year") +
                    ylab("Count") +
                    facet_grid(id~.)
Comments