我有这样的数据表结构,我很挣扎如何绘制两行来清楚地表明两个条件:
> 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(...)
但是这种解决方案并没有满足我的需求。我正在寻找另一种方法来做到这一点,因为我的桌子是以上述形式准备的。
与ggplot
library(ggplot2)
ggplot(df, aes(x=Dependent, y=Counts, group=Indication, color=Indication)) + geom_line()
如果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()通过删除冗余行而不丢失任何信息来重构数据帧。
有关spread
和tidyr
的更多信息,请查看here。
最后,我找到了我正在寻找的确切答案。
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))
感谢您提供的帮助和讨论。