我们可以使用scale_fill_discrete()函数来更改ggplot箱线图的图例名称。具体方法如下所示:
# 导入必要的库
library(ggplot2)
# 构建数据集
df <- data.frame(group = rep(c("A", "B"), each = 10),
value = c(rnorm(10), rnorm(10, 1)),
type = c(rep("Type 1", 5), rep("Type 2", 5), rep("Type 1", 5), rep("Type 2", 5)))
# 构建箱线图
p <- ggplot(df, aes(x = group, y = value, fill = type)) +
geom_boxplot()
# 设置图例名称
p <- p + scale_fill_discrete(name = "Legend Name")
# 显示图形
print(p)
我们可以'name”参数设置为所需的图例名称,如上面的代码示例所示。这样就可以更改ggplot箱线图的图例名称了。