有没有办法覆盖 scale_colour_manual 名称

Is there is a way to override scale_colour_manual name

我的密码是

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") 但这会覆盖颜色并给我完全不同的颜色 它会给出这个警告;

Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale.

有什么想法吗?

您可以使用参数 name

更新 colScale 的名称
colScale$name<-"type"

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

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

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

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)