【问题标题】:How can I change the legend linetype in ggplot2?如何更改 ggplot2 中的图例线型?
【发布时间】:2020-04-10 10:41:10
【问题描述】:

我有一个简单的绘图,我无法使用 scale_linetype_manual 根据绘图中的线型更改图例中的线型。

生成情节的代码是:

library(ggplot2)

x_1 <- rep(0:6, each = 2)
pdf_1 <- c(0,0.05,0.05,0.1,0.1,0.15,0.15,0.3,0.3,0.25,0.25,0.15,0.15,0)

x_2 <- rep(3:9, each = 2)
pdf_2 <- c(0,0.05,0.05,0.1,0.1,0.15,0.15,0.3,0.3,0.25,0.25,0.15,0.15,0)

data_1 <- data.frame(x_1, pdf_1,x_2,pdf_2)

ggplot()+
  geom_line(data=data_1,aes(x=x_1, y=pdf_1, color="Forecaster_1"),linetype='solid',size=1)+
  geom_line(data=data_1,aes(x=x_2, y=pdf_2, color="Forecaster_2"),linetype='dashed',size=1)+
  labs(x = "x") +
  labs(y = "PDF") +
  scale_colour_manual(values = c('Forecaster_1' = 'cornflowerblue', 'Forecaster_2' = 'coral2')) +
  scale_linetype_manual(values = c('Forecaster_1' = 'solid', 'Forecaster_2' = 'dashed')) 

希望有人能帮我解决这个问题。

【问题讨论】:

  • 您的代码不会为线型生成比例。因此scale_linetype_manual 无效。您需要先重塑数据。看看这篇文章的大致思路:Plotting two variables as lines using ggplot2 on the same graph(但不是哈德利的回答)
  • 这能回答你的问题吗? Add legend to ggplot2 line plot
  • @markus 我总是不愿意使用那个作为欺骗目标正是因为那个免责声明......也许有人可以让哈德利删除或更新他的答案
  • @markus 谢谢。有什么方法可以修复图例而不重塑和添加组变量?

标签: r ggplot2 legend


【解决方案1】:

您可以像这样覆盖默认图例:

ggplot() +
  geom_line(
    data = data_1,
    aes(
      x     = x_1,
      y     = pdf_1,
      color = "Forecaster_1"
    ),
    linetype = 'solid', 
    size = 1
  ) +
  geom_line(
    data = data_1,
    aes(
      x = x_2,
      y = pdf_2,
      color = "Forecaster_2"
    ),
    linetype = 'dashed',
    size = 1
  ) +
  labs(x = "x") +
  labs(y = "PDF") +
  scale_colour_manual(
    values = c('Forecaster_1' = 'cornflowerblue', 'Forecaster_2' = 'coral2'),
    guide = guide_legend(
      override.aes = list(
        linetype = c("solid", "dotted")
      )
    )
  )

linetype 可以替换为here 列出的任何值。

【讨论】:

    【解决方案2】:

    最好将线型映射为美学,然后确保为两个指南使用相同的名称。例如

    ggplot()+
      geom_line(data=data_1,aes(x=x_1, y=pdf_1, color="Forecaster_1", linetype='Forecaster_1'),size=1)+
      geom_line(data=data_1,aes(x=x_2, y=pdf_2, color="Forecaster_2", linetype='Forecaster_2'),size=1)+
      labs(x = "x") +
      labs(y = "PDF") +
      scale_colour_manual("Line", values = c('Forecaster_1' = 'cornflowerblue', 'Forecaster_2' = 'coral2')) +
      scale_linetype_manual("Line", values = c('Forecaster_1' = 'solid', 'Forecaster_2' = 'dashed'))
    

    【讨论】:

    • 这个也可以!我只需要将 LINE 参数添加到 scale 语句中。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-06-02
    • 2018-12-18
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    相关资源
    最近更新 更多