【问题标题】:How to plot two lines on a same plot, from a single data table/ data frame如何从单个数据表/数据框中在同一个图上绘制两条线
【发布时间】:2016-09-19 08:32:50
【问题描述】:

我有这样的数据表结构,我很挣扎我怎么能画两条线来清楚地表明两个条件:

> Dependent   Counts     Indication
> 0           2          Stay   
> 1           4          Stay 
> 2           1          Stay
> 0           11         Left 
> 1           5          Left 
> 2           3          Left  
> 3           2          Left   
> 4           1          Left

[顺便说一句] 我看到了一些参考/问题,并提供了解决方案 单图双线绝对可以通过以下方式实现:

x <- c(...)
y1 <- c(...)
y2 <- c(...)

但是这种解决方案并没有满足我的需求。我正在寻找另一种方法来做到这一点,因为我的桌子是以上述形式准备的。

【问题讨论】:

  • 也许我没有说清楚,但我希望有 x 轴(从属),y 轴(计数),我将有两条线分别用于“留”或“左”条件。
  • 感谢 @maRtin 帮助我以更易读的形式组织表格。

标签: r ggplot2 plot


【解决方案1】:

如果df 是您的数据框:

df <- data.frame("Dependent"=c(0,1,2,0,1,2,3,4),
                 "Counts"=c(2,4,1,11,5,3,2,1),
                 "Indication"=c("Stay","Stay","Stay","Left","Left","Left","Left","Left"))

library(tidyr)
df_tidy <- spread(df, Indication, Counts)

plot(df_tidy$Dependent, df_tidy$Left, type="l")
lines(df_tidy$Dependent, df_tidy$Stay, col="red")

我首先使用tidyr“传播”您的数据框,然后您可以使用标准绘图功能。

传播:

此函数获取键值格式的数据并返回一个 矩形整齐单元格格式。 如您所见,spread() 通过删除冗余行来重构数据帧,而不会丢失任何信息。

有关spreadtidyr的更多信息,请查看here

【讨论】:

  • 嗨,马丁,感谢您回答我的问题。但也许我没有说清楚,我希望有 x 轴(依赖),y 轴(计数),我将有两条线分别用于“留”或“左”条件。
  • 万分感谢!我访问了你的网站,我觉得你的 tidyr 是一个很酷的功能! :) 顺便说一句,我运行了代码,输出图并不完全是我想要的。最后我找到了我正在寻找的确切解决方案: ggplot() + geom_line(aes(subset(dataStay_Left$Dependents, dataStay_Left$ind=="Stay"), subset(dataStay_Left$Counts, dataStay_Left$ind=="Stay) "), group=1)) + geom_line(aes(subset(dataStay_Left$Dependents, dataStay_Left$ind=="Left"), 子集(dataStay_Left$Counts, dataStay_Left$ind=="Left"), group=2))不过,编写代码的方式可能很混乱。 :P
【解决方案2】:

用ggplot

library(ggplot2)
ggplot(df, aes(x=Dependent, y=Counts, group=Indication, color=Indication)) + geom_line()

【讨论】:

  • 嗨,Sandipan,感谢您回答我的问题。但也许我没有说清楚,我希望有 x 轴(依赖),y 轴(计数),我将有两条线分别用于“留”或“左”条件。
  • @Chun 我明白了,根据您的要求更新了上面的代码。
  • 嗨,Sandipan,哇,它好用,而且代码本身非常清晰!千恩万谢!我真的学到了一些东西:)
【解决方案3】:

我终于找到了我正在寻找的确切答案。

ggplot() + geom_line(aes(subset(dataStay_Left$Dependents,
dataStay_Left$ind=="Stay"), subset(dataStay_Left$Counts, 
dataStay_Left$ind=="Stay"), group=1)) + 
geom_line(aes(subset(dataStay_Left$Dependents, dataStay_Left$ind=="Left"), 
subset(dataStay_Left$Counts, dataStay_Left$ind=="Left"), group=2))

感谢提供的帮助和讨论。

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 2019-06-12
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 2020-07-23
    相关资源
    最近更新 更多