将文本放在有空白处的r图中

发布于 2025-02-12 09:40:32 字数 524 浏览 1 评论 0原文

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

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)

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

I need to add some text to several different plots in R. The best location for this text will depend on where each particular plot has no(t many) points, to minimize text/point overlap. Example:

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

Is there a way (preferably with base R) to automatically get a good placement for the text in each plot, instead of me having to first look at each plot and then set 5, 100 and 3, 0.5 manually?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饮湿 2025-02-19 09:40:32

我不知道任何内置功能,但是编写一个功能来计算最空虚的象限并不难。 @jay.sf的评论提到了“概念”等。这些关键字适用于Legend,但似乎在文本中不起作用,因此我将使用gudence代码>写文本。首先,现在的功能

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')

I do not know of any built-in function, but it is not hard to write a function to compute the emptiest quadrant. The comment by @jay.sf mentioned "topright" etc. Those keywords work for legend but do not seem to work in text so I will use legend to write the text. First, the function

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])
}

Now you can just compute the best location for the legend.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文