添加图例并划分绘图

时间:2017-09-06 21:55:34

标签: 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.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")

3 个答案:

答案 0 :(得分:3)

您可以在绘图底部添加颜色比例以指示部分。像这样:

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()

enter image description here

您甚至可以按部分填写背景,但之后我会使用线型而不是颜色来区分线条。

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()

enter image description here

答案 1 :(得分:0)

回答第一个问题:

D3DX10CreateDeviceAndSwapChain()

答案 2 :(得分:0)

我不确定拆分你所说的情节的定义是什么,但如果你想让它看起来像这样,这就回答了你的第二个问题:

A faceted plot

# Converts numbers from 1 to 48 into one of (A, AA, B, ... D, DD)
codify <- function(value) {
         c(
           rep('D', 3),  #  1 to 3 
           rep('A', 6),  #  4 to 9
           rep('B', 6),  # 10 to 15
           rep('C', 6),  # 16 to 21
           rep('D', 3),  # 22 to 24
           rep('DD', 6), # 25 to 27
           rep('AA', 6), # 28 to 33
           rep('BB', 6), # 34 to 39 (I'm assuming you meant BB goes from 34)
           rep('CC', 6), # 40 to 45 (I'm assuming you meant BB goes from 34)
           rep('DD', 3)  # 46 to 48 (I'm assuming you meant BB goes from 34)
           )[value]
}


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

ggplot(df,
       aes(x=x,y=y)) +
  geom_line(aes(y=y),colour="red") +
  geom_line(aes(y=z),colour="green") +
  facet_wrap(~type)