ggplot标签新行开头存在多余空格,如何实现左对齐?
问题描述
使用ggplot绘制图表并添加多行标签时,部分新行开头出现多余空格,导致标签无法左对齐,需要优化实现所有标签左对齐。
原代码如下:
library(tidyverse) library(metrica) df = data.frame(x = 1:100 * rnorm(100,50,7), y = c(1:100)) label <- df %>% summarise(R2 = metrica::R2(obs = y, pred = x)$R2, RMSE = metrica::RMSE(obs = y, pred = x)$RMSE, rRMSE = metrica::RRMSE(obs = y, pred = x)$RRMSE, n = n()) %>% mutate(label = paste("R² = ", round(R2, 2), "\nRMSE = ", round(RMSE, 2), "\nrRMSE = ", round(rRMSE, 2), '\nn = ',n, sep='')) plt <- ggplot(df,aes(x=x,y=y)) + geom_point() + geom_text(data = label, aes(x = -Inf, y = Inf, label = label), hjust = -0.1, vjust = 1.1,size=4); plt
问题图示:
解决方案
方法1:使用glue构建标签(推荐)
glue能直观拼接字符串,避免手动加空格出错,代码更易读:
label <- df %>% summarise(R2 = metrica::R2(obs = y, pred = x)$R2, RMSE = metrica::RMSE(obs = y, pred = x)$RMSE, rRMSE = metrica::RRMSE(obs = y, pred = x)$RRMSE, n = n()) %>% mutate(label = glue::glue("R² = {round(R2, 2)} RMSE = {round(RMSE, 2)} rRMSE = {round(rRMSE, 2)} n = {n}"))
方法2:修正paste写法
如果坚持用paste,改用paste0(默认sep=''),同时确保换行后无多余空格:
mutate(label = paste0("R² = ", round(R2, 2), "\nRMSE = ", round(RMSE, 2), "\nrRMSE = ", round(rRMSE, 2), "\nn = ", n))
优化对齐效果
调整geom_text的hjust参数为0,确保标签完全左对齐:
geom_text(data = label, aes(x = -Inf, y = Inf, label = label), hjust = 0, vjust = 1.1, size=4)
以上修改后,所有标签行将实现左对齐,不会出现多余空格。
内容的提问来源于stack exchange,提问作者Squan Schmaan
相关产品推荐
相关产品推荐

