Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot multiple lines in one graph [duplicate]

Tags:

Trying to use ggplot to plot multiple lines into one graph, but not sure how to do so with my dataset. Not sure whether I need to change the datastructure or not (transpose?)

Data looks like this:

Company   2011   2013 Company1  300    350 Company2  320    430 Company3  310    420 

I also tried it transposed:

Year   Company1  Company2  Company3 2011   300       320       310  2013   350       430       420 

And for this I can plot 1 of the values using;

ggplot(data=df, aes(x=Year, y=Company1)) + geom_line(colour="red") + geom_point(colour="red", size=4, shape=21, fill="white") 

But I don't know how to combine all the companies as I don't have an object 'Company' anymore to group on. Any suggestions?

like image 269
Chrisvdberge Avatar asked Jun 17 '13 14:06

Chrisvdberge


People also ask

How do you duplicate a graph?

Select the Excel chart (single click) and then right click to choose Copy. Move to a different location in the same worksheet or add a new worksheet and then right click and choose Paste. This gives you an exact copy of the chart so it is linked to the original data range and has the same formatting.

How do you plot multiple lines on a graph in R?

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.


2 Answers

You should bring your data into long (i.e. molten) format to use it with ggplot2:

library("reshape2") mdf <- melt(mdf, id.vars="Company", value.name="value", variable.name="Year") 

And then you have to use aes( ... , group = Company ) to group them:

ggplot(data=mdf, aes(x=Year, y=value, group = Company, colour = Company)) +     geom_line() +     geom_point( size=4, shape=21, fill="white") 

enter image description here

like image 167
Beasterfield Avatar answered Nov 03 '22 01:11

Beasterfield


Instead of using the outrageously convoluted data structures required by ggplot2, you can use the native R functions:

tab<-read.delim(text=" Company 2011 2013 Company1 300 350 Company2 320 430 Company3 310 420 ",as.is=TRUE,sep=" ",row.names=1)  tab<-t(tab)  plot(tab[,1],type="b",ylim=c(min(tab),max(tab)),col="red",lty=1,ylab="Value",lwd=2,xlab="Year",xaxt="n") lines(tab[,2],type="b",col="black",lty=2,lwd=2) lines(tab[,3],type="b",col="blue",lty=3,lwd=2) grid() legend("topleft",legend=colnames(tab),lty=c(1,2,3),col=c("red","black","blue"),bg="white",lwd=2) axis(1,at=c(1:nrow(tab)),labels=rownames(tab)) 

R multiple lines plot

like image 45
Federico Giorgi Avatar answered Nov 03 '22 01:11

Federico Giorgi