【问题标题】:Is there is a way to override scale_colour_manual name有没有办法覆盖 scale_colour_manual 名称
【发布时间】:2016-01-19 10:22:58
【问题描述】:

我的代码是

myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(software_length$type)
colScale <- scale_colour_manual(values = myColors,name="Software")

在 ggplot 中我使用了这个定义的手动颜色 colScale ,比如

 ggplot(data, aes(efficiency)) + theme_gray() + colScale 

但我想将名称从 Software 更改为 type ,我尝试使用 scale_color_discrete(name="type") 但这会覆盖颜色并给我完全不同的颜色 它会给出这个警告;

“颜色”的比例已经存在。添加另一个比例尺 'color',它将替换现有的比例。

有什么想法吗?

【问题讨论】:

    标签: r ggplot2 statistics


    【解决方案1】:

    另一种选择是将您的自定义比例重新定义为函数:

    myColors <- brewer.pal(5,"Set1")
    names(myColors) <- levels(software_length$type)
    
    my_col_scale <- function(name = "Software", ...) {
        scale_colour_manual(values = myColors, name = name, ...))
    }
    

    这样默认名称将为"Software",但您可以按正常方式调整该名称(或任何其他scale_colour_manual 设置)。

    ggplot(data, aes(efficiency)) + 
      theme_gray() +
      my_col_scale(name = "type")
    

    您可能还对scale_color_brewer 感兴趣...您的规模本质上是scale_color_brewer(palette = 1, name = "Software"),但它只有在有5 个级别时才有效(而scale_color_brewer 将在级别数量上灵活)。

    两个使用scale_color_brewer的例子:

    # the `cut` column has 5 levels
    ggplot(head(diamonds, 200), aes(x = carat, y = price, color = cut)) +
        geom_point() +
        scale_color_brewer(palette = 1)
    
    # the `clarity` column has 7 levels
    # scale_color_brewer makes the change automatically
    ggplot(head(diamonds, 200), aes(x = carat, y = price, color = clarity)) +
        geom_point() +
        scale_color_brewer(palette = 1)
    

    【讨论】:

    • 你的意思是不使用 scale_colour_manual ,而是使用 cale_color_brewer ?
    • 是的,我就是这个意思。
    • 这样的; myColors
    • 如果您使用scale_color_brewer,那么您无需担心brewer.palnames(myColors) --- 这一切都会自动处理。从字面上看,只需执行your_ggplot + scale_color_brewer(palette = 1),它将适用于可变数量的级别 - 直到该调色板的最大数量。查看修改。
    【解决方案2】:

    您可以使用参数name 更新colScale 的名称

    colScale$name<-"type"
    

    如果您不想全局更改,请使用不同的名称保存,然后更新

    colScale2<-colScale
    colScale2$name<-"type"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多