R 添加图例并划分情节

R 添加图例并划分情节,r,ggplot2,R,Ggplot2,我有以下可复制的代码 如何向该绘图添加图例以显示红色曲线表示y,绿色曲线表示z 如何将绘图划分为8个部分,如下所示: A=4-9,B=10-15,C=16-21,D=1,2,3,22,23和24,AA=28-33,BB=24-39,CC=40-45,DD=25,26,27,46,47和48 我的代码在这里: require(ggplot2) x <- 1:48 y <- rnorm(length(x)) z <- rnorm(length(x)) df <- data

我有以下可复制的代码

  • 如何向该绘图添加图例以显示红色曲线表示y,绿色曲线表示z
  • 如何将绘图划分为8个部分,如下所示: A=4-9,B=10-15,C=16-21,D=1,2,3,22,23和24,AA=28-33,BB=24-39,CC=40-45,DD=25,26,27,46,47和48
我的代码在这里:

require(ggplot2)
x <- 1:48
y <- rnorm(length(x))
z <- rnorm(length(x))
df <- data.frame(x, y, z)

ggplot(df, aes(x = x, y = y)) + 
  geom_line(aes(y = y), colour = "red") + 
  geom_line(aes(y = z), colour = "green")
require(ggplot2)

对第一个问题的回答:

library(ggplot2)
library(tidyr)

x <- 1:48
y <- rnorm(length(x))
z <- rnorm(length(x))
df <- data.frame(x,y,z)

df <- gather(df, 'y', 'z', key = "group", value = "value")

ggplot(df, aes(x = x, y = value, color = group)) +
geom_line() +
scale_color_manual(values=c("red", "green"))
库(ggplot2)
图书馆(tidyr)

x我不确定分割图的定义是什么,但这回答了你的第二个问题,如果你想让它看起来像这样:

library(tidyr)
library(ggplot2)
df1 <- data.frame(x = 1:48, y = rnorm(48), z = rnorm(48),
                  section = c(rep("D", 3), rep("A", 6), rep("B", 6), rep("C", 6), 
                              rep("D", 3), rep("DD", 3), rep("AA", 6), rep("BB", 6), 
                              rep("CC", 6), rep("DD", 3))

df1 %>% 
  gather(var, val, -x, -section) %>% 
  ggplot(aes(x, val)) + 
    geom_line(aes(color = var, group = var)) + 
    scale_color_manual(values = c("red", "green")) + 
    geom_rect(aes(xmin = x, xmax = lead(x), ymin = -Inf, ymax = min(val), fill = section)) + 
    scale_fill_brewer(palette = "Spectral") + 
    theme_bw()

#将1到48之间的数字转换为(A、AA、B、…D、DD)之一

codify您可以在绘图底部添加一个色标,以指示各个部分。大概是这样的:

library(tidyr)
library(ggplot2)
df1 <- data.frame(x = 1:48, y = rnorm(48), z = rnorm(48),
                  section = c(rep("D", 3), rep("A", 6), rep("B", 6), rep("C", 6), 
                              rep("D", 3), rep("DD", 3), rep("AA", 6), rep("BB", 6), 
                              rep("CC", 6), rep("DD", 3))

df1 %>% 
  gather(var, val, -x, -section) %>% 
  ggplot(aes(x, val)) + 
    geom_line(aes(color = var, group = var)) + 
    scale_color_manual(values = c("red", "green")) + 
    geom_rect(aes(xmin = x, xmax = lead(x), ymin = -Inf, ymax = min(val), fill = section)) + 
    scale_fill_brewer(palette = "Spectral") + 
    theme_bw()

当D和DD的值不连续时,很难理解它们是如何对应于“截面”的?我认为
BB
应该是34-39?这是关于在X轴的正确位置添加标签(A,B,…)。谢谢你的帮助,我要找的是没有多个绘图。我正在寻找一种方法,只需在X轴的正确位置添加(a,B,…)的标签。
df1 %>%  
  gather(var, val, -x, -section) %>% 
  ggplot(aes(x, val)) + 
    geom_line(aes(linetype = var, group = var)) + 
    geom_rect(aes(xmin = x, xmax = lead(x), ymin = -Inf, ymax = Inf, fill = section), 
              alpha = 0.2, show.legend = FALSE) + 
    scale_fill_brewer(palette = "Spectral") + 
    theme_bw()