【问题标题】:Plotting multiple sets of lines with sets nested in groups使用嵌套在组中的集合绘制多组线
【发布时间】:2019-11-07 21:03:38
【问题描述】:

我想绘制(使用 ggplot)多组线,其中线组嵌套在组内,即第 1 组由两条单独的线组成,第 2 组由两条单独的线组成等,但这些线应该具有相同的颜色跨组。我知道我可以使用循环来遍历这些组,但我想避免这种情况。结果应该与此类似(忽略粗线)。

此代码生成一个示例数据集。

y <- rep(NA, 60)
y[1] <- rnorm(1, 0, 0.5)
for (t in 2:60){
  y[t] <- rnorm(1, y[t - 1], 0.5)
}
n <- 2

data <- as.data.frame(cbind(rbind(cbind(rep(seq(1, 30), n), sort(rep(seq(1, n), 30)), y), cbind(rep(seq(1, 30), n), sort(rep(seq(1, n), 30)), y),cbind(rep(seq(1, 30), n), sort(rep(seq(1, n), 30)), y)), sort(rep(seq(1, 3), 30)))         )
colnames(data) <- c("t", "n", "y", "group")
data$y <- data$y + rnorm(3 * 30 * 2, 0, 0.1)

【问题讨论】:

    标签: r ggplot2 time-series


    【解决方案1】:

    我认为您的问题的答案已在此帖子中得到解决:Using geom_line with multiple groupings

    所以你可以在ggplot中使用interaction,根据你的数据,代码如下:

    library(ggplot2)
    g = ggplot(data,aes(x = t, y = y,group = interaction(as.factor(n),as.factor(group)),color = as.factor(group)))
    g + geom_line() 
    

    你应该得到你正在寻找的图表。

    【讨论】:

    • 这正是我想要的。谢谢!我没有看到之前的帖子。当我滚动浏览建议时,我认为它没有出现。s
    猜你喜欢
    • 1970-01-01
    • 2021-11-21
    • 2013-01-29
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多