Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot Multi line plot from same dataframe

Tags:

r

ggplot2

I have this dataframe (df) :

  day     time      value
20011101    93000 1.00000000
20011102    93000 1.00000000
20011105    93000 1.00000000
20011101   100000 0.81958763
20011102   100000 0.95412844
20011105   100000 0.27610209
20011101   103000 0.27835052
20011102   103000 0.32415902
20011105   103000 0.77958237
20011101   110000 0.23711340

Sample here: https://www.dropbox.com/s/y7mtcay6ke9ydnm/sample.txt

Using ggplot, I'm trying to get a line for every single day where axis x = time, so in R I wrote:

ggplot(df, aes(x=time, y=value, colour=day)) + geom_line()

Unfortunately, this is what I got. I did not expect a plot like this. Graph from R

And this is an Excel graph. This is the one I'm looking for. A different line for every single day:

enter image description here

I do not know how to tell R to join dots from same day... What's wrong? What am I missing?

One more thing: As I have data from more than 5 years, I would prefer a one-color plot.

Thanks for your help!

like image 797
user2261983 Avatar asked Jan 05 '14 00:01

user2261983


People also ask

How to plot 2 lines on same graph in ggplot?

In this method to create a ggplot with multiple lines, the user needs to first install and import the reshape2 package in the R console and call the melt() function with the required parameters to format the given data to long data form and then use the ggplot() function to plot the ggplot of the formatted data.

What does %>% mean in ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Introducing magrittr. Adding things to a ggplot changes the object that gets created.

How do you plot more than one variable in r?

You can create a scatter plot in R with multiple variables, known as pairwise scatter plot or scatterplot matrix, with the pairs function. In addition, in case your dataset contains a factor variable, you can specify the variable in the col argument as follows to plot the groups with different color.

Does ggplot work with Dataframe?

The dataframe is the first parameter in a ggplot call and, if you like, you can use the parameter definition with that call (e.g., data = dataframe ). Aesthetics are defined within an aes function call that typically is used within the ggplot call.


2 Answers

add group aes:

ggplot(df, aes(x=time, y=value, colour=day,group=day)) + geom_line()
like image 107
agstudy Avatar answered Sep 17 '22 02:09

agstudy


Convert your day to a factor, it's being treated as continuous right now.

df$day <- as.factor(df$day)
ggplot(df, aes(x=time, y=value, colour=day)) + geom_line()
like image 25
Gregor Thomas Avatar answered Sep 19 '22 02:09

Gregor Thomas