散点图中的文本标签与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

一个使用ggreject的示例。我需要在解决方案中添加一些填充,这样标签就不会与趋势线重叠。

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

ggreject包提供了避免文本重叠的功能。安装软件包后,请先加载它,然后再运行以下代码从我的机器上修改的代码:

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

希望这能帮助

最新更新