Wednesday, July 3, 2013

Plotting two or more lines using ggplot2


How would you go about with plotting 2 or more line graphs in the same graph with ggplot. There are simpler ways with plot() but I wanted to use ggplot2 because it's way cooler and i use melted data. But what about if your data is not melted, like my data below ? From the previous blog i’m using the same data frame so just follow along.
Dates Registrations.x Registrations.y
1   2013-01-01               7              21
2   2013-01-02              15              36
3   2013-01-03              13              23
4   2013-01-04              20              16
5   2013-01-05              14              28
6   2013-01-06              17              22



df <- data.frame(
 Registrations.x = c(7,15,13,20,14,17),
 Registrations.y = c(21,36,23,16,28,22
))
also add:-
> df$Dates <- c("2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05", "2013-01-06")
Now go ahead and run the following packages to make sure they are running


>require("reshape")
>require("ggplot2")
Conver to long format by melting the data frame.
>test_df <- melt(df, id="Dates")  


>ggplot(data=test_df, aes(x=Dates, y=value, colour=variable)) + geom_line()


I hit errors with “geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?” - i then dug a little deeper online and found out the solution is to add a group. The error message indicates that you need to specifie a group. Personally  message indicates almost nothing, as always in R :(. So i edited my plot with code below.
>ggplot(data=test_df, aes(x=Dates, y=value, colour=variable, group=variable)) + geom_line()
Bang, it then works like a charm?

No comments:

Post a Comment

Add any comments if it helped :)