geom_line:如何仅连接几个点 [英] geom_line : How to connect only a few points

查看:109
本文介绍了geom_line:如何仅连接几个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据框和这个情节:

I have this dataframe and this plot :

df <- data.frame(Groupe = rep(c("A","B"),4),
                 Period = gl(4,2,8,c("t0","t1","t2","t3","t4")),
                 rate = c(0.83,0.96,0.75,0.93,0.67,0.82,0.65,0.73))

ggplot(data = df, mapping = aes(y = rate, x = Period ,group = Groupe, colour=Groupe, shape=Groupe)) +
   geom_line(size=1.2) +
   geom_point(size=5) 

我如何组织数据,以使t1t2之间的点不与线相连?我希望连接t0t1(根据组为蓝色或红色),t2t3以相同的方式连接,但t1t2之间没有线.我通过研究类似的问题尝试了几件事,但它总是弄乱了我的分组颜色:/

How could i organize my data so that the points between t1 and t2 are not connected with a line ? I'd like t0 and t1 to be connected (blue or red according to the group), t2 and t3 connected in the same way, but no lines between t1 and t2. I tried several things by looking at similar questions, but it always mess up my grouping colors :/

推荐答案

在ggplot中处理此类问题的最佳方法通常是在数据框中创建一个附加列,该列指示您要在其中使用的分组数据.例如,在这里我向您的数据框添加了额外的列gp:

The best way to handle a problem like this in ggplot is often to create an additional column in your data frame that indicates the grouping you want to work with in your data. For example, here I've added an extra column gp to your data frame:

df$gp <- c(1,2,1,2,3,4,3,4)
ggplot(data = df, aes(y = rate, x = Period, group = gp, colour=Groupe, shape=Groupe)) +
  geom_line(size=1.2) +
  geom_point(size=5)

我相信结果就是您要寻找的东西:

The result is, I believe, what you are looking for:

如果将Period设为数字列而不是字符向量或因子,则可以更轻松地自动生成类似gp的列,而不是手动指定它(也许使用ifelsecases来创建它) )-如果您想多次执行相同的操作或使用较大的数据帧,这将非常有用.

If you make Period a numerical column rather than a character vector or factor, you can more easily generate a column like gp automatically rather than manually specifying it (perhaps using ifelse or cases to create it) - this would be useful if you wanted to do the same thing many times or with a large data frame.

这篇关于geom_line:如何仅连接几个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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