在一张图中绘制多条线 [英] Plot multiple lines in one graph

查看:206
本文介绍了在一张图中绘制多条线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用ggplot将多行代码绘制到一张图中,但不知道如何使用我的数据集。不知道是否需要更改数据结构(转置?)

数据如下所示:

 公司2011 2013 
公司1 300 350
公司2 320 430
公司3 310 420

我也试过换位:

 年份Company1 Company2 Company3 
2011 300 320 310
2013 350 430 420

为此我可以绘制1个值使用;

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

但我不知道如何组合所有公司,因为我再也没有对象'公司'了。任何建议吗?

解决方案

您应该将数据转化为长时间ggplot2 :

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

然后你必须使用 aes(...,group = Company)来对它们进行分组:

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


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?

解决方案

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")

这篇关于在一张图中绘制多条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆