ggplot2设置图例背景圆角遇‘unused argument’错误的解决问询
解决ggplot2设置圆角报错的问题
错误原因
你遇到的报错是因为ggplot2原生的element_rect()函数根本没有radius参数,不管传unit(0.1, "snpc")还是0.1都会被识别为无效参数,所以触发"unused argument"错误。
两种可行解决方案
方案1:用ggtext包的圆角矩形元素(推荐)
ggtext包提供了支持圆角的element_rect_round()函数,用法和element_rect()几乎一致,只是多了radius参数。
修改后的完整代码:
library(tidyverse) library(ggplot2) library(ggthemes) library(grid) library(ggtext) # 新增加载ggtext包 read.csv("/Users/benjamincohn/Desktop/R studio/vaccination_percentages.csv") -> un un %>% arrange(Uninsured) %>% ggplot(aes(y = Life.Expectancy.at.Birth..years., x = Uninsured, color = Location)) + geom_point() + scale_x_continuous(breaks = seq(2, 18, by = 1)) + scale_y_continuous(breaks = seq(70, 81, by = 1)) + geom_smooth(method = "lm", color = 'black') + ggtitle("Uninsured (%) vs. Life Expectancy at Birth (years) by State (2023)") + labs(y = "Life Expectancy at Birth (years)", x = "Uninsured (%)") + theme(axis.line = element_line(colour = "black", size = 1, linetype = "solid"), plot.background = element_rect_round(fill = "lightblue", radius = unit(0.1, "snpc")), # 替换为支持圆角的元素 legend.key = element_rect(fill = "deepskyblue3"), legend.background = element_rect_round(fill = "deepskyblue3", radius = unit(0.1, "snpc"))) # 替换为支持圆角的元素
方案2:用grid包自定义圆角元素(无需额外装包)
如果不想新增依赖,可以用grid包的roundrectGrob()创建圆角矩形,再通过annotation_custom()添加到图表中,适合需要精细控制位置的场景:
示例(以图例背景为例):
# 先绘制基础图表 p <- un %>% arrange(Uninsured) %>% ggplot(aes(y = Life.Expectancy.at.Birth..years., x = Uninsured, color = Location)) + geom_point() + scale_x_continuous(breaks = seq(2, 18, by = 1)) + scale_y_continuous(breaks = seq(70, 81, by = 1)) + geom_smooth(method = "lm", color = 'black') + ggtitle("Uninsured (%) vs. Life Expectancy at Birth (years) by State (2023)") + labs(y = "Life Expectancy at Birth (years)", x = "Uninsured (%)") + theme(axis.line = element_line(colour = "black", size = 1, linetype = "solid"), plot.background = element_rect(fill = "lightblue"), legend.key = element_rect(fill = "deepskyblue3"), legend.background = element_blank()) # 先清空默认图例背景 # 添加自定义圆角图例背景 library(grid) round_legend_bg <- roundrectGrob(x = 0, y = 1, width = 1, height = 1, r = unit(0.1, "snpc"), fill = "deepskyblue3", just = c("left", "top")) p + annotation_custom(round_legend_bg, xmin = Inf, xmax = Inf, ymin = -Inf, ymax = Inf)
内容的提问来源于stack exchange,提问作者lubalubadubdub
相关产品推荐
相关产品推荐

