简体   繁体   English

如何从单个数据表/数据框在同一图上绘制两条线

[英]How to plot two lines on a same plot, from a single data table/ data frame

I have such data table structure, and I am so struggle how could I plot two line to clearly indicate two condition: 我有这样的数据表结构,我很挣扎如何绘制两条线以清楚地表明两种情况:

> 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

[Btw] I saw some reference/ question asked and solution provided Dual line on single plot could definitely achievable by: [顺便说一句]我看到了一些参考/问题,并提出了解决方案,前提是可以通过以下方式绝对可以实现单图上的双线:

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

But this kind of solution did not hit my needs. 但是这种解决方案没有满足我的需求。 I am seeking another way to do this as my table is prepared in the above-mentioned form. 我正在寻找另一种方式来完成此任务,因为我的桌子是以上述形式准备的。

if df is your dataframe: 如果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")

I am first using tidyr to "spread" your dataframe and from there you can use the standard plot function. 我首先使用tidyr来“扩展”您的数据tidyr ,然后您就可以使用标准绘图功能了。

Spread: 传播:

This function takes data that is in a key-value format and returns a rectangular tidy cell format. 此函数获取键值格式的数据并返回 矩形整齐的单元格格式。 As you can see spread() restructures the dataframe by removing redundant rows without losing any information. 如您所见,spread()通过删除冗余行而不丢失任何信息来重构数据帧。

For more information on spread and tidyr , please look here . 有关spreadtidyr更多信息,请点击这里

with ggplot 与ggplot

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

Finally I worked out the exact answer I am looking for. 最后,我找到了想要的确切答案。

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

Thanks for the help provided and the discussion. 感谢您提供的帮助和讨论。

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

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