How to draw a line chart include 2 or more lines?

20 views
Skip to first unread message

Humphrey Zhao

unread,
Sep 21, 2014, 9:27:54 PM9/21/14
to ggp...@googlegroups.com
In my analysis, I gathered a serial data about the number of post during 6 years. I separated 6 years with 24 seasons and gain the table in the document "pdp.csv".
I want to draw a line chart use ggplot2 with "Period" as x axis, and "NoPX" as y axis(just like the line chart in the CSV). However, no matter how hard I have tried, I can draw 1 line in the graph only. When I add other column using "line" or "geom_line", an error will occur and that line won't add on the graph. May I ask how can I draw all lines on the graph? Thanks a lot. 
 
pdp.csv

Ben Bond-Lamberty

unread,
Sep 22, 2014, 8:31:51 AM9/22/14
to Humphrey Zhao, ggplot2
The best, though not only, way to do this is to reshape your data
frame into 'long' format first:

d <- read.csv("pdp.csv")
library(reshape2)
dmelted <- melt(d, id.vars=1)

This produces a data frame with columns Period, variable, and value. Then simply

library(ggplot2)
ggplot(dmelted,aes(Period,value,color=variable))+geom_line()

Ben
> --
> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> Please provide a reproducible example:
> https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>
> ---
> You received this message because you are subscribed to the Google Groups
> "ggplot2" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ggplot2+u...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages