代码之家  ›  专栏  ›  技术社区  ›  Kim

R ggplot2::geom\u vline图例未正确显示线型

  •  1
  • Kim  · 技术社区  · 8 年前

    我正在尝试这个简单的任务,我希望在ggplot对象中添加两条垂直线,使用不同的颜色和线型,并在图例中正确指定颜色/线条。我一直在看 this post 其中两个 geom_vline 绘制。如果将其中一种线型更改为实线,图例将错误地显示线型。它将所有直线转换为实体。

    library(ggplot2)
    library(ggthemes)
    ggplot(aes(x = Sepal.Length), data = iris) + 
      geom_histogram(color = 'black', fill = NA) + 
      geom_vline(aes(xintercept = median(iris$Sepal.Length),
                     color = "median"), 
                 linetype = "solid", size = 1) +
      geom_vline(aes(xintercept = mean(iris$Sepal.Length),
                     color = "mean"), 
                 linetype = "dashed", size = 1) +
      scale_color_manual(
        name = "statistics", 
        values = c(median = "blue", mean = "red"))
    

    enter image description here

    我还简单地尝试了以下操作,没有添加任何数据:

    library(ggplot2)
    library(ggthemes)
    ggplot() + theme_bw() + 
      geom_vline(aes(xintercept = c(0, 0.2), 
                     color = c("Zero", "Pooled")), 
                 size = 1, linetype = c("solid", "dotdash")) +
    scale_color_manual(
      name = "statistics", 
      values = c(Zero = "black", Pooled = "blue"))
    

    其中线型错误地显示在图例上。

    enter image description here

    有人能告诉我发生了什么事情,以及我如何才能正确显示线型吗?

    1 回复  |  直到 8 年前
        1
  •  5
  •   Marius    8 年前

    你可以把 linetype 在 aes 呼叫,就像你对颜色所做的那样:

    ggplot(aes(x = Sepal.Length), data = iris) + 
        geom_histogram(color = 'black', fill = NA) + 
        geom_vline(aes(xintercept = median(iris$Sepal.Length),
                       color = "median", linetype = 'median'), 
                   size = 1) +
        geom_vline(aes(xintercept = mean(iris$Sepal.Length),
                       color = "mean", linetype = "mean"), 
                   size = 1) +
        scale_color_manual(
            name = "statistics", 
            values = c(median = "blue", mean = "red")) +
        scale_linetype_manual(
            name = "statistics", 
            values = c(median = "solid", mean = "dashed"))
    

    在指定哪个值与哪个线型匹配时使用命名向量也有帮助-我认为第二个示例失败的原因是,在图例中,ggplot按字母顺序将线型指定给各个级别。

    输出:

    enter image description here

    推荐文章