首页 > 解决方案 > R - ggplot 自定义图例

问题描述

我在 R 中的 ggplot 中创建了图形,除了图例之外,我实际上对此非常满意,我只想在其中包含颜色和线型变化的图例。

我的代码是:

x <- data.frame(
    "type" = c("new", "new", "old", "old", "new", "new", "old", "old"), 
    "date" = as.Date(c("2018-01-01", "2018-01-01", "2018-01-01", "2018-01-01", "2018-01-08", "2018-01-08", "2018-01-08", "2018-01-08")),
    "score" = c("1.5", "2.5", "2.6", "3.7", "5.2", "8.6", "5.2", "8.6"),
    "category" = c("actual", "predicted", "actual", "predicted", "actual", "predicted", "actual", "predicted"),
    stringsAsFactors = F)

  library(ggplot2)

  ggplot(x, aes(x=date, y=score, group = paste(category, type), linetype = category, colour = paste(category, type))) + 
    geom_line(size = 1.25) +
    scale_color_manual(
      values = c("#4286f4", "#f9026d", "#4286f4", "#f9026d")
    )

结果应该是

提议的图像

标签: rggplot2

解决方案


我相信以下内容可以满足问题的要求。它的灵感来自这个问题的答案。诀窍是使labels和 的比例与和name相等。为了使代码更简单, 我已经编辑了这些列并开始了。scale_color_manualscale_linetype_manual
pastecategorytype

library(ggplot2)

colr <- paste(x$category, x$type)

ggplot(x, aes(x = date, y = score, 
              group = colr, 
              linetype = colr, 
              colour = colr)) + 
  geom_line(size = 1.25) +
  scale_color_manual(
    values = c("#4286f4", "#f9026d", "#4286f4", "#f9026d"),
    labels = sort(unique(colr)),
    name = "category and type"
  ) +
  scale_linetype_manual(values = c(1, 1, 3, 3),
                        labels = sort(unique(colr)),
                        name = "category and type")

在此处输入图像描述


推荐阅读