[r] Plot multiple lines in one graph

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?

This question is related to r ggplot2 linegraph

The answer is


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


The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.

plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) )  )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
  } 
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))