【问题标题】:ggplot add segments to scatter plot according to factorsggplot根据因素将段添加到散点图中
【发布时间】:2020-08-27 01:57:52
【问题描述】:

我有以下“代码”

set.seed(100)
values<-c(rnorm(200,10,1),rnorm(200,2.1,1),rnorm(250,6,1),rnorm(75,2.1,1),rnorm(50,9,1),rnorm(210,2.05,1))
rep1<-rep(3,200)
rep2<-rep(0,200)
rep3<-rep(1,250)
rep4<-rep(0,75)
rep5<-rep(2,50)
rep6<- rep(0,210)
group<-c(rep1,rep2,rep3,rep4,rep5,rep6)
df<-data.frame(values,group)

我想将这些数据绘制为散点图(如附图)并添加段。这些段(y 值)应代表给定组数据的平均值。此外,根据因素(组),段应具有不同的颜色。有没有一种有效的方法来做到这一点 ggplot ? 非常感谢

【问题讨论】:

    标签: r ggplot2 scatter segment


    【解决方案1】:

    我们可以通过稍微扩充您的数据来做到这一点。我们将使用dplyr 来获得group 的平均值,并且我们将创建一个变量来提供观察指数,并且每次group 变化时都会增加一个(这将有助于您获得细分想要):1

    library(dplyr)
    
    df <- df %>%
        mutate(idx = seq_along(values), group = as.integer(group)) %>%
        group_by(group) %>%
        mutate(m = mean(values)) %>%
        ungroup() %>%
        mutate(group2 = cumsum(group != lag(group, default = -1)))
    

    现在我们可以制作情节了;使用geom_line()group2 分组,每次组更改时都会更改,从而生成您想要的段。然后我们只需按group 的(离散化版本)着色:

    ggplot(data = df, mapping = aes(x = idx, y = values)) +
        geom_point(shape = 1, color = "blue") +
        geom_line(aes(x = idx, y = m, group = group2, color = as.factor(group)),
                  size = 2) +
        scale_color_manual(values = c("red", "black", "green", "blue"),
                           name = "group") +
        theme_bw()
    


    1https://stackoverflow.com/a/42705593/8386140

    【讨论】:

      猜你喜欢
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 2018-11-12
      • 2019-05-08
      • 2011-07-13
      • 1970-01-01
      • 2015-09-29
      相关资源
      最近更新 更多