r - 如何使用 geom_segments 进行抖动
问题描述
我在 ggplot 中使用 geom_segments 链接了两个点。它适用于 geom_point但是当我使用 geom_jitter 它并没有给我想要的结果。我想查看它们之间的所有点。你能帮我如何使用geom_jitter连接点吗?为什么点看起来不平行?
ggplot() +
geom_point(data = mydata, aes(x = lower, y = lower_p)) +
geom_point(data = mydata, aes(x = higher, y = higher_p)) +
geom_segment(aes(x = lower, y = ifelse(lower_p!= higher_p, NA, lower_p), xend = higher, yend =
higher_p), data = mydata)
解决方案
由于没有发布示例数据,我使用一些虚拟数据来说明一些事情。让我们设置一下:
df <- data.frame(x = c(1,1,1,2,2),
xend = c(2,2,2,3,3),
y = c(1,1,1,2,2),
yend = c(1,1,1,2,2))
如果我们绘制类似于您发布的内容,我们会得到以下图,其中点被过度绘制 2-3 次:
ggplot(df) +
geom_point(aes(x, y), colour = "red") +
geom_point(aes(xend, yend), colour = "dodgerblue") +
geom_segment(aes(x = x, y = y, xend = xend, yend = yend))
现在知道这geom_jitter()
是geom_point(position = "jitter")
. 像大多数职位一样,你可以给出position_jitter()
你希望如何发生抖动的论据。例如,我们可能只想在 y 方向上抖动:
ggplot(df) +
geom_point(aes(x, y), colour = "red",
position = position_jitter(height = 0.1, width = 0)) +
geom_point(aes(xend, yend), colour = "dodgerblue",
position = position_jitter(height = 0.1, width = 0)) +
geom_segment(aes(x = x, y = y, xend = xend, yend = yend),
position = position_jitter(height = 0.1, width = 0))
正如你所看到的,这看起来很可怕,因为每个点都是独立于其他点抖动的。我们可以通过设置抖动的种子来更接近我们想要的:
ggplot(df) +
geom_point(aes(x, y), colour = "red",
position = position_jitter(height = 0.1, width = 0, seed = 1)) +
geom_point(aes(xend, yend), colour = "dodgerblue",
position = position_jitter(height = 0.1, width = 0, seed = 1)) +
geom_segment(aes(x = x, y = y, xend = xend, yend = yend),
position = position_jitter(height = 0.1, width = 0, seed = 1))
这现在按预期处理左侧点(因为种子应该对每个点进行相同的随机过程),但会弄乱右侧点。发生这种情况是因为这些与左点同时抖动为后续数字,而不是与左点平行。
唯一合理的解决方案似乎是预先计算抖动并使用它,以便每个点都相同:
set.seed(0)
df$jit <- runif(nrow(df), -0.05, 0.05)
ggplot(df) +
geom_point(aes(x, y + jit), colour = "red") +
geom_point(aes(xend, yend + jit), colour = "dodgerblue") +
geom_segment(aes(x = x, y = y + jit, xend = xend, yend = yend + jit))
推荐阅读
- android - 刷新小部件上的现有数据
- excel - 跨工作表的 Excel VBA 克隆(命名)表
- clojure - clj-http 异常:ExceptionInfo clj-http: 状态 415 clj-http.client/wrap-exceptions/fn--1863 (client.clj:196)
- amazon-web-services - AWS - 使用 EC2 实例的 FailedInvocations
- php - 在 PHP 中从数组创建多维树对象
- ruby-on-rails - 如何集成 Google Places gem 以获取 Google 评论
- linux - Qt:有时在旋转鼠标滚轮时不会立即调用wheelEvent()
- kubernetes - 如何在 Kubernetes 中使用 Apache ActiveMQ Artemis
- reactjs - 如何在 react-admin 中的按钮单击回调中调用反应钩子,或者该怎么做?
- asp.net - ASP.NET core 3 使用 jwt 自定义身份验证