简体   繁体   English

在一个图中绘制多条线

[英]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. 尝试使用ggplot将多行绘制成一个图形,但不确定如何使用我的数据集。 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; 为此我可以使用绘制1个值;

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? 有什么建议?

You should bring your data into long (ie molten) format to use it with ggplot2 : 您应该将数据转换为长(即熔化)格式,以便与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: 然后你必须使用aes( ... , group = Company )对它们进行分组:

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

在此输入图像描述

Instead of using the outrageously convoluted data structures required by ggplot2, you can use the native R functions: 您可以使用本机R函数,而不是使用ggplot2所需的令人费解的数据结构:

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多行图

The answer by @Federico Giorgi was a very good answer. @Federico Giorgi的答案是一个非常好的答案。 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. 因此,我做了以下操作,为了从单个数据集的数据在同一个图中生成多行,我使用了for循环。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM