gpt4 book ai didi

r - 将文本放在 R 图中有空白的地方

转载 作者:行者123 更新时间:2023-12-05 02:27:54 25 4
gpt4 key购买 nike

我需要在 R 中的几个不同绘图中添加一些文本。此文本的最佳位置将取决于每个特定绘图没有(很多)点的位置,以最大程度地减少文本/点重叠。示例:

par(mfrow = c(1, 2))
plot(cars)
text(5, 100, "some text here.", adj = 0, cex = 0.7)
plot(iris[ , 3:4])
text(3, 0.5, "some text here.", adj = 0, cex = 0.7)

enter image description here

有没有办法(最好使用 base R)自动为每个图中的文本找到一个好的位置,而不是我必须先查看每个图然后设置 5、1003, 0.5 手动?

最佳答案

我不知道有什么内置函数,但是编写一个函数来计算最空象限并不难。 @jay.sf 的评论提到了“topright”等。这些关键字适用于 legend 但似乎不适用于 text 所以我将使用 legend 写入文本。一、功能

emptyQuadrant = function(x) {
mid1 = sum(range(x[,1]))/2
mid2 = sum(range(x[,2]))/2
Q1 = sum(x[,1]>=mid1 & x[,2]>=mid2)
Q2 = sum(x[,1]<=mid1 & x[,2]>=mid2)
Q3 = sum(x[,1]<=mid1 & x[,2]<=mid2)
Q4 = sum(x[,1]>=mid1 & x[,2]<=mid2)
BestQ = which.min(c(Q1, Q2, Q3, Q4))
return(c("topright", "topleft",
"bottomleft", "bottomright")[BestQ])
}

现在您只需计算图例的最佳位置即可。

par(mfrow = c(1, 2))
plot(iris[ , 1:2])
legend(emptyQuadrant(iris[,1:2]), "some text here.", cex = 0.7, bty='n')
plot(iris[ , 3:4])
legend(emptyQuadrant(iris[,3:4]), "some text here.", cex = 0.7, bty='n')

Plots with carefully placed text

关于r - 将文本放在 R 图中有空白的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72841627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com