【问题标题】:Plot certain columns of a data frame绘制数据框的某些列
【发布时间】:2013-12-28 17:17:25
【问题描述】:

我的数据框具有以下名为 dat 的结构:

  No.  Action  Title          Replies  PlusOnes  Reshares  Url                    
   1    Share   SomeTitle     2        3         1         http://plus.google.com 
   2    Post    AnotherTitle  3        4         5         http://plus.google.com

这是我数据的dput(dat)

structure(list(No. = 1:2, Action = c("Share", "Post"), Title = c("Some Title", 
"Another Title"), Replies = 2:3, PlusOnes = 3:4, Reshares = c(1L, 
5L), Url = c("http://plus.google.com", "http://plus.google.com"
)), .Names = c("No.", "Action", "Title", "Replies", "PlusOnes", 
"Reshares", "Url"), class = "data.frame", row.names = c(NA, -2L
))

如何在图表中绘制 RepliesPlusOnesReshares 列? x 轴应该是No.,y 轴是回复/PlusOnes/Reshares 的数量,并且这些列应该在图表中各有一条线。

问候

【问题讨论】:

  • 我看到您已经努力格式化您的数据,但最好保持原样(只需复制和粘贴)或更好地显示 dput(请参阅我的编辑)

标签: r graph plot


【解决方案1】:

您可以通过两种方式做到这一点:使用标准 R 图形或 ggplot2(我更喜欢)。

由于另一个答案解释了如何使用 matplot 来完成此操作,我将向您展示另一种获得漂亮图表的方法。

require(ggplot2)
require(reshape2)
dat<-data.frame('No.'=1:2,replies=2:3,PlusOnes=3:4,Reshares=c(1,5))
melted=melt(dat,id.vars='No.')

ggplot(melted,aes(x=factor(No.),y=value,color=factor(variable),group=factor(variable)))+
geom_line()+xlab('No.')+guides(color=guide_legend("Series"))+
labs(title="Insert Title Here")

本质上发生的事情是reshape2包中的melt()函数将为No.的每个级别的每个可能的列值创建一个新的行条目它还在每一行中存储与其对应的值的变量名,所以很容易用 ggplot 绘制类似的东西。

【讨论】:

    【解决方案2】:

    类似:

    with(dat,matplot(x=No.,y=cbind(Replies,PlusOnes,Reshares),type="l")
    

    【讨论】:

      【解决方案3】:

      使用lattice(我编辑添加了第三个变量)

      xyplot(Replies+Reshares+PlusOnes~factor(No.),
             data=dat,type='l',auto.key=T)
      

      【讨论】:

        猜你喜欢
        • 2016-02-17
        • 1970-01-01
        • 1970-01-01
        • 2019-07-21
        • 1970-01-01
        • 2020-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多