R语言 ggplot根据x轴变量而不是分组变量垂直连接线?

hm2xizp9  于 2023-04-09  发布在  其他
关注(0)|答案(3)|浏览(118)

我想绘制一个有多条线的线图。我有三个条件,我想为每个条件绘制一条有三个点的线。出于某种原因,ggplot是垂直连接线,所以不是三条水平线连接一组内的三个点,我有三条垂直线连接一组点之间的所有点,在x轴上的一个点。我不能计算出我做错了什么。
这是我的代码:

#this is a list of 9 numbers to be plotted in 3 lines on the y axis
means <- c(574.7685, 580.7797, 574.9977, 575.3367, 584.8480, 574.8543, 574.7309, 585.2841, 574.1599)

#defining the groups that I want to plot separate lines for
group <- c(1,1,1,2,2,2,3,3,3)

#The x axis categories
Measurement_Time <- c("0-Pre-adaptation","5-post","60-post")
 
#put the above in a dataframe
mean_red <- data.frame(Measurement_Time, group, means)

#plot
ggplot(mean_red, aes(x = Measurement_Time, y = means, colour = group)) + geom_line()

输出为:
This problem plot
当我想要的是:
This sensible plot
任何帮助赞赏,谢谢!

w8ntj3qf

w8ntj3qf1#

我认为问题是Map到颜色的内容需要是分类的,而最终在x轴上的内容应该是数字的,就像这样:

library(tidyverse)

mean_red <- tibble(
  means = rep(c(575, 580, 575), times = 3) + rnorm(9, sd = 5),
  group = factor(c(1, 1, 1, 2, 2, 2, 3, 3, 3)),
  Measurement_Time = rep(1:3, times = 3)
)

ggplot(mean_red, aes(x = Measurement_Time, y = means, colour = group)) + geom_line()

创建于2023-04-06带有reprex v2.0.2

vhmi4jdf

vhmi4jdf2#

大家好,欢迎来到SO。
当简单地使用视觉美学Map不足以区分组时,则还需要提供groups美学。请参阅:https://ggplot2.tidyverse.org/reference/aes_group_order.html
此外,您应该在dataframe中将groups设置为因子,以便ggplot将其解释为离散项,而不是连续变量。
在我下面的代码中,我生成了数据,因为你的示例代码中有你没有提供的变量(min 15,hour 1,hour 4)。下次请包括它们!

library(ggplot2)
    
    set.seed(12345)
    
    #this is a list of 9 numbers to be plotted in 3 lines on the y axis
    means <- sample(1:10, 9, replace = TRUE)
    
    #defining the groups that I want to plot separate lines for
    group <- c(1,1,1,2,2,2,3,3,3)
    group <- as.factor(group)
    
    #The x axis categories
    Measurement_Time <- c("0-Pre-adaptation","5-post","60-post")
    
    #put the above in a dataframe
    mean_red <- data.frame(Measurement_Time, group, means)
    
    #plot
    ggplot(mean_red, aes(x = Measurement_Time, y = means, colour = group, group = group)) + 
        geom_line()

创建于2023-04-06带有reprex v2.0.2

5f0d552i

5f0d552i3#

由于我们不知道means应该如何排序,所以看起来有点棘手。但从外观上看,您在aes()中缺少group变量。

ggplot(mean_red, aes(x = Measurement_Time, y = means, group = group, colour = group)) +
    geom_line()

相关问题