【问题标题】:Is there are a way to change the breaks of a ggplot legend without changing other properties of the aesthetic?有没有办法在不改变美学的其他属性的情况下改变 ggplot 图例的中断?
【发布时间】:2021-08-28 23:32:10
【问题描述】:

我希望更改 ggplot 图例的中断而不影响美学的其他属性(例如,调色板、名称等)。例如,美学是colour的MWE:

## Original plot:
df <- data.frame(x = 1:10, y = 1:10, z = 1:10)
gg <- ggplot(df, aes(x, y, colour = z)) + 
  geom_point() + 
  scale_colour_distiller(palette = "Spectral", name = "Original title")
gg

## Plot with adjusted breaks:
gg + scale_colour_distiller(breaks = c(2.5, 7.5))

Original plot

Plot with adjusted breaks

在第二个图中,调色板和图例名称被重置为其默认值:我只想更改图例中断。

我明白为什么上述方法不起作用;第一个色阶完全被第二个色阶取代。但是,我不知道如何解决这个问题。非常感谢任何建议!

【问题讨论】:

  • 为什么不在一个函数中使用所有参数? scale_colour_distiller(palette = "Spectral", name = "Original title", breaks = c(2.5,7.5))
  • 我需要在 情节创建之后更改中断。应该在我的原始帖子中提到这一点。

标签: r ggplot2


【解决方案1】:

我写了一个函数来解决我的问题。它采用ggplot 对象、美学名称(作为字符串)以及对应图例的breaks

change_legend_breaks <- function(gg, aesthetic, breaks) {

  ## Find the scales associated with the specifed aesthetic
  sc <- as.list(gg$scales)$scales
  all_aesthetics <- sapply(sc, function(x) x[["aesthetics"]][1]) 
  idx <- which(aesthetic == all_aesthetics) 
  
  ## Overwrite the breaks of the specifed aesthetic
  gg$scales$scales[[idx]][["breaks"]] <- breaks
  
  return(gg)
} 

这是我第一次在低级别处理 ggplot 对象,所以也许有更好、更健壮的方法:不过,这对我有用。 有趣的是,它似乎是一个变异函数,也就是说,它改变了绘图对象本身,而不是对象的副本。我不知道这在 R 中是可能的。

为了检查该功能是否按预期工作,这里是原始 MWE 的一个变体,这一次有两个美学:

df <- data.frame(x = 1:10, y = 1:10, z1 = 1:10, z2 = 1:10)
gg <- ggplot(df, aes(x, y, colour = z1, size = z2)) + 
  geom_point() + 
  scale_size(name = "Original size title") + 
  scale_colour_distiller(palette = "Spectral", name = "Original colour title") 

change_legend_breaks(gg, "colour", breaks = c(2.5, 7.5))
change_legend_breaks(gg, "size", breaks = c(1, 9))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2019-08-28
    • 1970-01-01
    • 2018-05-09
    • 2018-04-13
    相关资源
    最近更新 更多