【问题标题】:How to change color legend from continues to discrete colors in ggplot2?如何在ggplot2中将颜色图例从连续颜色更改为离散颜色?
【发布时间】:2020-04-15 09:25:16
【问题描述】:

我使用 ggplot2 创建了一个折线图,并且颜色图例是连续的。我想将其更改为离散的彩色线条。我有以下代码:

library(ggplot2)
ggplot(df, aes(L)) +
 geom_line(aes(y = Updated, colour = S, group = S, linetype = "Updated")) +
 geom_line(aes(y = Current, colour = S, group = S, linetype = "Current")) +
 scale_color_gradient() +
 labs(x = element_text("Span Length (ft)"), y = element_blank(), 
         title = "Moment Live Load Distribution Factors \n Exterior Girder - Multi Lane",
      linetype = "AASHTO", color = "Spacing (ft)") +
  scale_linetype_manual(values = c(1, 3),
                        labels = c("Updated", "Current")) +
    theme_classic() +
    theme(plot.title = element_text(hjust = 0.5, margin = margin(0,0,20,0), size = 18),
          legend.position="top",
          legend.box.background = element_rect(colour = "black", size = 0.5),
          legend.box.margin = margin(0,0,0,0), legend.background = element_blank())

目前我的图表看起来像

我想将图例的连续部分转换为与图例其余部分宽度相同的彩色线条。谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您有多种选择,具体取决于变量的含义:

    将变量转换为因子:

    library(ggplot2)
    
    
    ggplot(mtcars) +
      geom_line(aes(mpg, wt, colour = factor(cyl)))
    

    reprex package (v0.3.0) 于 2020-04-15 创建

    使用合并图例:

    ggplot(mtcars) +
      geom_line(aes(mpg, wt, colour = cyl)) +
      scale_color_binned(guide = guide_coloursteps())
    

    reprex package (v0.3.0) 于 2020-04-15 创建

    请注意,guide = guide_coloursteps() 目前没有任何作用,但可以帮助您自定义图例。

    【讨论】:

    • 小评论;该问题要求图例中的离散彩色线条,因此guide = guide_legend() 似乎更合适。
    • 谢谢,我尝试使用 colour = factor(S), group = factor(S),但收到错误消息:错误:提供连续刻度的离散值
    • 还有一个问题,现在只显示一些图例项(5 个中有 3 个是 S 的大小)。关于如何让 S 中的所有图例项目显示的任何想法
    • 这让我回到了连续的传奇
    • 我回到色块而不是线条
    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2015-02-24
    • 2023-03-28
    相关资源
    最近更新 更多