【问题标题】:ggplot with both `geom_vline` and `geom_hline`. Task: need separate legends带有 `geom_vline` 和 `geom_hline` 的 ggplot。任务:需要单独的图例
【发布时间】:2021-11-16 03:42:01
【问题描述】:
library(tidyverse)
library(lubridate)

y <- rnorm(100)

df <- tibble(y) %>% 
  mutate(os = factor(rep_len(1:5, 100)),
         date = seq(from = ymd('2013-01-01'), by = 1, length.out = 100))

ggplot(df, aes(x = date, y = y, colour = os)) +
  geom_line() +
  geom_vline(
    aes(xintercept = min(date), linetype = 'os 1'), 
    colour = 'red') +
  geom_vline(
    aes(xintercept = median(date), linetype = 'os 2'), 
    colour = 'blue') +
  geom_hline(
    aes(yintercept = 1, linetype = "dashed"),
    colour = "black"
  ) +
  scale_linetype_manual(
    name = 'lines',
    values = c('os 1' = 1, 'os 2' = 1),
    guide = guide_legend(override.aes = list(colour = c('red', 'blue')))) 

输出:

输出有什么问题:

  1. geom_hline 丢失。
  2. 图例将 vline 和 hline 组合成十字形。

正确的输出:

  1. 应该绘制geom_hline。
  2. 需要为 vlines 和 hlines 提供单独的图例。即,vline 图例中的线条应该是垂直的,而 hline 图例中的线条应该是水平的。

【问题讨论】:

    标签: r ggplot2 geom-vline


    【解决方案1】:

    这可以通过

    来实现
    1. hline 添加到scale_linetype_manual
    2. answer 中使用自定义键字形。
    library(tidyverse)
    library(lubridate)
    
    set.seed(123)
    
    y <- rnorm(100)
    
    df <- tibble(y) %>% 
      mutate(os = factor(rep_len(1:5, 100)),
             date = seq(from = ymd('2013-01-01'), by = 1, length.out = 100))
    
    draw_key_cust <- function(data, params, size) {
      if (data$colour %in% c("red", "blue"))
        draw_key_vpath(data, params, size)
      else
        draw_key_path(data, params, size)
    }
    
    ggplot(df, aes(x = date, y = y, colour = os)) +
      geom_line() +
      geom_vline(
        aes(xintercept = min(date), linetype = 'os 1'), 
        colour = 'red', key_glyph = "cust") +
      geom_vline(
        aes(xintercept = median(date), linetype = 'os 2'), 
        colour = 'blue', key_glyph = "cust") +
      geom_hline(
        aes(yintercept = 1, linetype = "dashed"), 
        colour = "black", key_glyph = "cust"
      ) +
      scale_linetype_manual(
        name = 'lines',
        values = c('os 1' = 1, 'os 2' = 1, dashed = 2),
        guide = guide_legend(override.aes = list(colour = c('red', 'blue', 'black')))) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 2022-06-22
      • 2022-11-21
      相关资源
      最近更新 更多