gpt4 book ai didi

r - 如何使用 "jitter"生成相同的图,以及如何抖动选定的点(不是所有点)?

转载 作者:行者123 更新时间:2023-12-02 11:11:58 24 4
gpt4 key购买 nike

我想做的是:

a) 让 ggplot 代码每次运行时生成的图都相同 [set.seed 是一种概念吗?] 和

b) 仅对具有相同 y 轴值的标签进行抖动文本标签 - 保留其他文本标签。这似乎是某种基于点因子值的条件抖动。

这是一些数据:

dput(df)
structure(list(Firm = c("a verylongname", "b verylongname", "c verylongname",
"d verylongname", "e verylongname", "f verylongname", "g verylongname",
"h verylongname", "i verylongname", "j verylongname"), Sum = c(74,
77, 79, 82, 85, 85, 88, 90, 90, 92)), .Names = c("Firm", "Sum"
), row.names = c(NA, 10L), class = "data.frame")

这是使用 df 的 ggplot 代码:

ggplot(df, aes(x = reorder(Firm, Sum, mean), y = Sum)) +
geom_text(aes(label = Firm), size = 3, show.guides = FALSE, position = position_jitter(height = .9)) +
theme(axis.text.x = element_blank()) +
scale_x_discrete(expand = c(-1.1, 0)) + # to show the lower left name fully
labs(x = "", y = "", title = "")

请注意,该图的一个版本仍然与 h 和 i 重叠——每次运行上述代码时,文本标签的位置都会发生变化。

enter image description here

顺便说一句,这个问题conditional jitter稍微移动 x 轴上的离散值,但我想(仅)移动 y 轴上的重叠点。

最佳答案

一种选择是添加一列来标记重叠点,然后分别绘制它们。更好的选择可能是直接移动重叠点的 y 值,以便我们可以直接控制它们的位置。我在下面展示了这两个选项。

选项 1(抖动):首先,添加一列来标记重叠。在这种情况下,因为这些点几乎落在一条线上,所以如果它们的 y 值太接近,我们可以将任何点标记为重叠。如果检查 x 值是否接近也很重要,您可以包含更复杂的条件。

df$overlap = lapply(1:nrow(df), function(i) {
if(min(abs(df[i, "Sum"] - df$Sum[-i])) <= 1) "Overlap" else "Ignore"
})

在图中,我将抖动点涂成红色,这样很容易看出哪些点受到了影响。

# Add set.seed() here to make jitter reproducible
ggplot(df, aes(x = reorder(Firm, Sum, mean))) +
geom_text(data=df[df$overlap=="Overlap",],
aes(label = Firm, y = Sum), size = 3,
position = position_jitter(width=0, height = 1), colour="red") +
geom_text(data=df[df$overlap=="Ignore",],
aes(label = Firm, y = Sum), size = 3) +
theme(axis.text.x = element_blank()) +
scale_x_discrete(expand = c(-1.1, 0)) + # to show the lower left name fully
labs(x = "", y = "", title = "")

enter image description here

选项 2(直接放置):另一个选项是直接控制标签移动的量,而不是采用发生给我们的任何抖动。在这种情况下,我们知道我们想要以相同的 y 值移动每对点。如果我们需要同时担心 x 和 y 值、同一重叠中的两个以上点,和/或我们需要移动接近但不完全相同的值,则需要更复杂的逻辑。

library(dplyr)

# Create a new column that shifts pairs of points with the same y-value by +/- 0.25
df = df %>% group_by(Sum) %>%
mutate(SumNoOverlap = if(n()>1) Sum + c(-0.25,0.25) else Sum)

ggplot(df, aes(x = reorder(Firm, Sum, mean), y = SumNoOverlap)) +
geom_text(aes(label = Firm), size = 3) +
theme(axis.text.x = element_blank()) +
scale_x_discrete(expand = c(-1.1, 0)) + # to show the lower left name fully
labs(x = "", y = "", title = "")

enter image description here

注意:要使抖动可重现,请在抖动绘图代码之前添加 set.seed(153) (或任何您想要的种子值)。

关于r - 如何使用 "jitter"生成相同的图,以及如何抖动选定的点(不是所有点)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32527713/

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