如何在ggplot中绘制垂直大括号?含现有代码调试需求
问题:在ggplot回归图中添加垂直大括号失败
需要在第六张教学用回归图中添加两个垂直大括号,尝试ggbrace包的stat_brace未成功,现有代码如下,需修正第六张图的大括号部分。
解决方案
原代码中stat_brace的参数设置存在两个核心问题:
- 错误启用
inherit.data=T,导致继承主数据的x/y映射,干扰大括号的自定义坐标 - 大括号的坐标范围与旋转角度匹配不当,无法生成正确的垂直样式
修正后的第六张图代码,调整stat_brace参数,取消数据继承,精准设置大括号的起止坐标与旋转方向,确保垂直大括号正确显示:
# 第六张图:添加垂直大括号后的版本 ggplot(data, aes(x = x, y = y)) + geom_point(color = "gray") + geom_point(data = data_sample1, aes(x = x, y = y), color = "#F8766D") + geom_smooth(method = "lm", color = "black", se = FALSE) + geom_smooth(data = data_sample1, method = "lm", color = "#F8766D", se = FALSE) + labs(title = "Population and sample regression Lines", x = "Years of education", y = "Log of earnings") + theme_minimal() + theme(legend.position = "none") + # 总体误差项标注与垂直大括号 annotate("text", x = 1, y = 4.5, label = expression(u[i] == y[i] - beta[0] - beta[1] * x[i]), parse = TRUE, size=3.5, col="#F8766D") + stat_brace(aes(x = c(2.8, 2.8), y = c(0.9, 7.5)), rotate = 270, size = 0.5, col = "#F8766D", inherit.data = FALSE) + # 样本残差项标注与垂直大括号 annotate("text", x = 4.5, y = 3.5, label = expression(hat(u)[i] == y[i] - hat(beta)[0] - hat(beta)[1] * x[i]), parse = TRUE, size=3.5, col="#F8766D") + stat_brace(aes(x = c(2.2, 2.2), y = c(0.9, 5.3)), rotate = 270, size = 0.5, col = "#F8766D", inherit.data = FALSE)
关键修正说明
- 取消
inherit.data=T,彻底避免主数据的x/y映射覆盖大括号的自定义坐标 - 垂直大括号的x坐标设为固定值(如
c(2.8,2.8)),y坐标设为上下端点,通过rotate=270实现垂直方向 - 若需要调整大括号的开口方向,可将
rotate参数改为90(反向垂直)
内容的提问来源于stack exchange,提问作者Rubén Pérez Sanz
相关产品推荐
相关产品推荐

