英文:
How can you suppress the "Scale for ‘fill’ is already present" warning from ggplot2 when replacing the scale?
问题
ggplot2库在替换填充比例尺(scale fill)时会产生以下众所周知的警告:
填充比例尺已存在。
添加另一个填充比例尺,它将替换现有的比例尺。
通常的情况下,可以按以下方式产生这个警告:
library("ggplot2")
data <- data.frame(group = LETTERS[1:3], value = 1:9)
figure <- ggplot(data, aes(x = group, y = value, fill = group)) +
geom_boxplot() +
scale_fill_manual(values = c("#1b98e0", "yellow", "#353436")) +
scale_fill_discrete(guide = guide_legend(reverse = TRUE)) # 产生填充比例尺警告
print(figure)
虽然通常的建议是简单地不要替换填充比例尺,但我们正在使用一个具有默认渲染方案的库调用,而且代码不能被编辑。然而,出于可访问性的目的,我们允许用户覆盖调色板,这将导致警告出现。
是否有一种方法可以仅抑制ggplot2中的填充比例尺警告?
英文:
The library ggplot2 produces the following well known warning when replacing the scale fill:
Scale for fill is already present.
Adding another scale for fill, which will replace the existing scale.
Which is typically produced as follows:
library("ggplot2")
data <- data.frame(group = LETTERS[1:3], value = 1:9)
figure <- ggplot(data, aes(x = group, y = value, fill = group)) +
geom_boxplot() +
scale_fill_manual(values = c("#1b98e0", "yellow", "#353436")) +
scale_fill_discrete(guide = guide_legend(reverse = TRUE)) # Produces scale fill warning
print(figure)
While the typical recommendation is to simply not replace the scale fill, we are using a library call that has a default rendering scheme defined and the code cannot be edited. However, for the purposes of accessibility we allow the user to override the palette, which in turn will produce the warning.
Is there a way to suppress only the scale fill warning from ggplot2?
答案1
得分: 1
最佳实践要求尽可能避免生成警告,因为警告抑制可能会隐藏其他可能的问题。但是,在这种情况下,由于意图是替换最初定义的填充比例,可以使用与从绘图中删除比例相同的方法,即:
# 定义一个基本绘图
library("ggplot2")
data <- data.frame(group = LETTERS[1:3], value = 1:9)
figure <- ggplot(data, aes(x = group, y = value, fill = group)) +
geom_boxplot()
# 删除任何比例
figure$scales$scales <- list()
# 现在定义我们自己的比例
figure <- figure + scale_fill_manual(values = c("#1b98e0", "yellow", "#353436"))
print(figure)
英文:
Best practices call for preventing a warning from being generated if possible since warning suppression can hide other possible problems. However, in this case since the intent is the replacement of the originally defined scale fill it is possible to use the same approach as removing the scale from a plot, namely:
# Define a basic plot
library("ggplot2")
data <- data.frame(group = LETTERS[1:3], value = 1:9)
figure <- ggplot(data, aes(x = group, y = value, fill = group)) +
geom_boxplot()
# Remove any scales
figure$scales$scales <- list()
# Now define our own scale
figure <- figure + scale_fill_manual(values = c("#1b98e0", "yellow", "#353436"))
print(figure)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论