首页 > 解决方案 > 如何将我的点与线连接,但在 gpplot 中按不同的组?

问题描述

我正在尝试制作我的点与线相连的图表。我遇到的问题是我在同一列下的点与不同的值相关联,所以当我添加geom_line它时,它作为 1 行遍历所有组。如何分隔线,使其仅连接具有相同变量的点?

这是一些示例代码

temps = data.frame(Temperature= c(15,25,35), 
                                    Growth.Phase = c("exponential", "stationary", "death"),
                                    Carbohydrates = sample(c(3:10), 9, replace = T))

temps$Shape = if_else(temps$Growth.Phase == "exponential", 21,
                      if_else(temps$Growth.Phase == "stationary", 22, 23))

我想要 3 行,每行用相同的符号连接点,但是当我使用 ```geom_line`` 时......

ggplot(data = temps, aes(x = Temperature, y = "Proportions")) +
  geom_point(aes(y = Carbohydrates),colour = "darkred", 
             fill = "darkred", shape = temps$Shape, size = 3) +
  geom_line(aes(y = Carbohydrates))

我得到这张图片

在此处输入图像描述

有谁知道如何解决这一问题?

标签: rggplot2

解决方案


您可以将shape第一个美学放入其中,然后将其用作geom_line分组变量

ggplot(data = temps, aes(x = Temperature, y = "Proportions", shape = factor(Shape))) +
  geom_point(aes(y = Carbohydrates),colour = "darkred", 
             fill = "darkred", size = 3) +
  geom_line(aes(y = Carbohydrates))

在此处输入图像描述

如果线条不垂直时点的顺序不正确,您可以使用temps %>% dplyr::arrange(Carbohydrates)


推荐阅读