如何使用ggplot通过线连接不同组的点 [英] How to connect points of different groups by a line using ggplot

查看:257
本文介绍了如何使用ggplot通过线连接不同组的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

df<-data.frame(adjuster=c("Mary","Mary","Bob","Bob"), date=as.Date(c("2012-1-1","2012-2-1","2012-3-1","2012-4-1")), value=c(10,15,25,15))
df
  adjuster       date value
1     Mary 2012-01-01    10
2     Mary 2012-02-01    15
3      Bob 2012-03-01    25
4      Bob 2012-04-01    15

ggplot(df,aes(x=date,y=value,color=adjuster))+geom_line()+geom_point()

在上图中,请注意2月和3月点之间的断开连接.如何用蓝线连接这些点,而使实际的3月点保持红色?换句话说,Bob应该与[Jan-Mar)中的值相关联,而Mary与[Mar-Apr]中的值相关联.

In the above graph, notice the disconnect between the February and March points. How do I connect those points with a blue line, leaving the actual March point red? In other words, Bob should be associated with the value from [Jan - Mar) and Mary from [Mar-Apr].

原来我的例子太简单了.列出的答案并不能推广到调节器在两个以上的人之间多次切换的情况.例如,考虑

Turns out my example was overly simple. The answers listed don't generalize to the case where the adjuster changes between two people on more than one occasion. For example, consider

df<-data.frame(adjuster=c("Mary","Mary","Bob","Bob","Mary"), date=as.Date(c("2012-1-1","2012-2-1","2012-3-1","2012-4-1","2012-5-1")), value=c(10,15,25,15,20))
      adjuster       date value
1     Mary 2012-01-01    10
2     Mary 2012-02-01    15
3      Bob 2012-03-01    25
4      Bob 2012-04-01    15
5     Mary 2012-05-01    20

由于我没有在原始问题中提及此问题,因此我将选择一个仅适用于原始数据的答案.

Since I didn't mention this in my original question, I'll pick an answer that simply worked for my original data.

推荐答案

已更新以最大程度地减少对data.frame的修改,并添加了group = 1参数

Updated to minimise tinkering with data.frame, added the group = 1 argument

稍微修改一下data.frame.我猜,您应该能够自动进行修补.如果不是,请告诉我.另外,根据您在问题中发布的图表,您的ggplot命令不起作用

Tinkered around with your data.frame a little. You should be able to automate the tinkering around, I guess. Let me know if you aren't. Also, your ggplot command wasn't working as per the chart you've posted in the question

df<-data.frame(
  adjuster=c("Mary","Mary","Bob","Bob"), 
  date=as.Date(c("2012-1-1","2012-2-1","2012-3-1","2012-4-1")), 
  value=c(10,15,25,15)
)

library(data.table)
library(ggplot2)
dt <- data.table(df)
dt[,adjuster := as.character(adjuster)]
dt[,prevadjuster := c(NA,head(adjuster,-1))]
dt[is.na(prevadjuster),prevadjuster := adjuster]


ggplot(dt) +
geom_line(aes(x=date,y=value, color = prevadjuster, group = 1)) +
geom_line(aes(x=date,y=value, color = adjuster, group = 1)) +
geom_point(aes(x=date,y=value, color = adjuster, group = 1))

这篇关于如何使用ggplot通过线连接不同组的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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