如何调整ggplot的vjust与hjust解决标注偏移/重叠问题
解决ggplot实际值vs预测值图中标注重叠/偏移问题
问题根源
你之前把所有指标标注都固定在x=Inf, y=-Inf同一个坐标点上,hjust和vjust仅控制文本自身的对齐方式,并非位置偏移参数,所以所有文本挤在同一点,必然出现重叠或偏移出图的情况。
可行解决方案
方案1:合并成多行文本(最简洁)
把所有指标用\n拼接成一个多行字符串,一次性标注在右下角,自动垂直排列,彻底避免重叠:
# 拼接所有指标为多行文本 metrics_text <- paste( paste("Model R-squared:", round(best_model_results$model_r2, 2)), paste("Test R-squared:", round(best_model_results$test_r2, 2)), paste("Correlation:", round(best_model_results$correlation, 2)), paste("MSE:", round(best_model_results$MSE, 2)), paste("Max Error:", round(best_model_results$max_error, 2)), sep = "\n" ) # 绘制图表并添加标注 gg <- ggplot(pred_results, aes(x = Actual, y = Predicted)) + geom_point(color = "blue", alpha = 0.7) + geom_abline(intercept = 0, slope = 1, color = "black", linetype = "dashed") + labs(title = "Test Set: Actual vs Predicted", x = "Actual (%)", y = "Predicted (%)") + theme_minimal() + # 把多行文本放在右下角,hjust=1右对齐,vjust=0让文本从该点向上排列 annotate("text", x = Inf, y = -Inf, hjust = 1, vjust = 0, label = metrics_text, size = 3.5)
方案2:逐个调整标注位置(更灵活)
如果需要单独控制每个标注的垂直位置,可以基于数据范围设置偏移量,让标注从右下角向上依次排列:
gg <- ggplot(pred_results, aes(x = Actual, y = Predicted)) + geom_point(color = "blue", alpha = 0.7) + geom_abline(intercept = 0, slope = 1, color = "black", linetype = "dashed") + labs(title = "Test Set: Actual vs Predicted", x = "Actual (%)", y = "Predicted (%)") + theme_minimal() + # 每个标注y值按数据比例递增,hjust=1右对齐 annotate("text", x = Inf, y = -Inf, hjust = 1, vjust = 0, label = paste("Model R-squared:", round(best_model_results$model_r2, 2))) + annotate("text", x = Inf, y = -Inf + diff(range(pred_results$Predicted))*0.03, hjust = 1, vjust = 0, label = paste("Test R-squared:", round(best_model_results$test_r2, 2))) + annotate("text", x = Inf, y = -Inf + diff(range(pred_results$Predicted))*0.06, hjust = 1, vjust = 0, label = paste("Correlation:", round(best_model_results$correlation, 2))) + annotate("text", x = Inf, y = -Inf + diff(range(pred_results$Predicted))*0.09, hjust = 1, vjust = 0, label = paste("MSE:", round(best_model_results$MSE, 2))) + annotate("text", x = Inf, y = -Inf + diff(range(pred_results$Predicted))*0.12, hjust = 1, vjust = 0, label = paste("Max Error:", round(best_model_results$max_error, 2)))
这里用diff(range(pred_results$Predicted))*0.03基于数据范围设置偏移,适配不同数据集无需硬编码数值。
方案3:用文本框包裹(更美观)
如果想让标注更整洁,可借助ggtext包添加带背景的文本框:
library(ggtext) gg <- ggplot(pred_results, aes(x = Actual, y = Predicted)) + geom_point(color = "blue", alpha = 0.7) + geom_abline(intercept = 0, slope = 1, color = "black", linetype = "dashed") + labs(title = "Test Set: Actual vs Predicted", x = "Actual (%)", y = "Predicted (%)") + theme_minimal() + geom_richtext( x = Inf, y = -Inf, hjust = 1, vjust = 0, label = metrics_text, fill = "white", alpha = 0.9, size = 3.5, label.padding = unit(0.3, "lines"), label.r = unit(0.1, "lines") )
内容的提问来源于stack exchange,提问作者NEERAJ YADAV
相关产品推荐
相关产品推荐

