散点图中的文本标签不与 r 中的趋势线重叠(ggplot)

Text labels in scatterplot not overlapping trend line in r (ggplot)

我正在尝试使用 ggplot 创建散点图。有没有办法阻止我的文本标签与趋势线重叠?

我只能停止相互重叠文本标签。

rownames = c("dummy", "dummy", "dummy", "dummy", "dummy", "dummy","dummy", "dummy", "dummy", "dummy")
corr_truth = c(-0.39, -0.13, 0.28, -0.49, -0.14, 0.52, 0.43, 0.22, -0.29, -0.02)
corr_pred= c(-0.41, 0.01, 0.36, -0.38, -0.28, 0.44, 0.26, 0.24, -0.38, -0.23)
corr_complete = data.frame(rownames, corr_truth,corr_pred)

plot_corr_complete = ggplot(data = corr_complete, aes(corr_truth, corr_pred)) + geom_point() + 
  xlim(-0.5,0.7) + 
  ylim(-0.5,0.7) +
  geom_text(label = corr_complete$rownames, nudge_x = 0.08, nudge_y = 0.005, check_overlap = T) +
  geom_smooth(method = "lm", se = FALSE, color = "black")
plot_corr_complete

ggrepel 包提供了避免文本重叠的功能。 安装包后,在 运行 以下代码之前加载它 修改后的代码在我的机器上运行:

rownames = c("dummy", "dummy", "dummy", "dummy", "dummy", "dummy","dummy", "dummy", "dummy", "dummy")
corr_truth = c(-0.39, -0.13, 0.28, -0.49, -0.14, 0.52, 0.43, 0.22, -0.29, -0.02)
corr_pred= c(-0.41, 0.01, 0.36, -0.38, -0.28, 0.44, 0.26, 0.24, -0.38, -0.23)
corr_complete = data.frame(rownames, corr_truth,corr_pred)

plot_corr_complete = ggplot(data = corr_complete, aes(corr_truth, corr_pred, label = rownames)) + geom_point() + 
  xlim(-0.5,0.7) + 
  ylim(-0.5,0.7) +
  geom_text_repel() +
  geom_smooth(method = "lm", se = FALSE, color = "black")
plot_corr_complete

希望对您有所帮助

一个使用 ggrepel 的例子。我需要在解决方案中添加一些填充,因此标签不会与趋势线重叠。

library(tidyverse);library(ggrepel)
rownames = c("dummy", "dummy", "dummy", "dummy", "dummy", "dummy","dummy", "dummy", "dummy", "dummy")
corr_truth = c(-0.39, -0.13, 0.28, -0.49, -0.14, 0.52, 0.43, 0.22, -0.29, -0.02)
corr_pred= c(-0.41, 0.01, 0.36, -0.38, -0.28, 0.44, 0.26, 0.24, -0.38, -0.23)
corr_complete = data.frame(rownames, corr_truth,corr_pred)

plot_corr_complete = ggplot(data = corr_complete, aes(corr_truth, corr_pred)) + geom_point() + 
  xlim(-0.5,0.7) + 
  ylim(-0.5,0.7) +
  geom_text_repel(label = corr_complete$rownames,point.padding = 0.2,
                  nudge_y = 0.005, nudge_x = 0.02) +
  geom_smooth(method = "lm", se = FALSE, color = "black")
plot_corr_complete