【问题标题】:Remove some legend entries in ggplot删除 ggplot 中的一些图例条目
【发布时间】:2021-08-20 18:22:41
【问题描述】:

我想删除我的ggplot 中的一些图例条目。

以前,这可以通过在相关的scale 中定义breaks 参数来实现,如here 所述。但是,最近的更新似乎破坏了该功能。

例子:

ggplot(mtcars) + 
  
  geom_col(aes(x = 1:nrow(mtcars), y = disp, fill = paste(cyl))) +
  
  scale_fill_manual(values = c("grey50", "grey60", "grey70"),
                    breaks = c("4"))

虽然这段代码 sn-p 只显示一个图例项,但它不允许控制未显示元素的颜色。

省略breaks 属性:

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    使用命名values 参数:

    ggplot(mtcars) + 
      geom_col(aes(x = 1:nrow(mtcars), y = disp, fill = paste(cyl))) +
      scale_fill_manual(values = c("4" = "red", "6" = "green", "8" = "blue"),
                        breaks = c("4"))
    

    【讨论】:

    • 感谢您的回复。如果我使用诸如scale_fill_viridis_d 之类的预定义比例,我该如何实现?
    • @mzuba 不要在scale_fill_viridis_d 中指定values 参数。
    猜你喜欢
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 2016-06-07
    • 1970-01-01
    相关资源
    最近更新 更多