r - Amplitude lines + geom_point in ggplot2
问题描述
I would like to add a some aditional lines to this plot. I must to show the distance for max and min data, from horizontal and vertical, like the example below.
Is like to add boxplots without the boxes
I have tried follow this example, but without success. Avoid plot overlay using geom_point in ggplot2
I did this on photoshop. But, how can i add on R?
Original plot
plot <- ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(gear))) +
geom_point() +
ggtitle("Cars")
plot
Modded version
解决方案
我对此非常好奇,但发现我的首选cowplot
, 并不能很好地划分情节。包作者自己建议使用patchwork
更复杂的间距和对齐方式。使用cowplot
,我制作了一个假人ggplot
将右上角作为空白区域,但无法获得正确的高度。patchwork
而是具有plot_spacing
执行此操作的功能。
第一项任务是制作用于绘制线条的汇总数据框。我添加了一个行号,因此有一种方法可以垂直堆叠上边距的线条,水平堆叠右边距的线条。(我想是一个虚拟值,并且position_dodge
可能也有效。)
library(tidyverse)
library(patchwork)
summaries <- mtcars %>%
group_by(gear) %>%
summarise(minwt = min(wt), maxwt = max(wt), minmpg = min(mpg), maxmpg = max(mpg)) %>%
ungroup() %>%
mutate(row = row_number())
summaries
#> # A tibble: 3 x 6
#> gear minwt maxwt minmpg maxmpg row
#> <dbl> <dbl> <dbl> <dbl> <dbl> <int>
#> 1 3 2.46 5.42 10.4 21.5 1
#> 2 4 1.62 3.44 17.8 33.9 2
#> 3 5 1.51 3.57 15 30.4 3
ggplot
我使用相同的基础制作了顶部和右侧的图,并给出了它们theme_void
,因此除了线段本身之外什么都没有显示。我建议用不同的主题来完成这个,这样你就可以看到这些情节是如何结合在一起的。
summary_base <- ggplot(summaries, aes(color = factor(gear)))
top <- summary_base +
geom_segment(aes(x = minwt, xend = maxwt, y = row, yend = row), show.legend = F) +
theme_void()
right <- summary_base +
geom_segment(aes(x = row, xend = row, y = minmpg, yend = maxmpg), show.legend = F) +
theme_void()
然后是主线:
points <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(gear))) +
geom_point() +
theme(legend.position = "bottom")
然后patchwork
允许您将图添加在一起。他们从左到右,从上到下,所以为了获得右上角的空白,我使用了plot_spacer
. 然后plot_layout
设置网格。您可以根据需要调整相对高度和宽度——可能使它们更窄。这是我第一次使用patchwork
,但它非常简单。
top + plot_spacer() + points + right +
plot_layout(ncol = 2, nrow = 2, widths = c(1, 0.2), heights = c(0.2, 1))
由reprex 包(v0.2.0)于 2018 年 7 月 11 日创建。
推荐阅读
- r - 在 igraph 中识别和量化集群类型
- r - ggplot2用日期注释构面错误
- sql-server - 如何将 geoJSON 坐标输入到 SQL Server 数据库?
- java - 来自按钮的 JavaFX 输入
- r - 在 dplyr::summarize_at 中使用 tidyeval 时出现“参数“e2”缺失且没有默认值”错误
- mysql - 尝试编写一个查询来获取最高和最低收入并打印帐户健康状况?
- google-cloud-platform - Cloud Bigtable 似乎没有删除应该被垃圾收集的数据
- python - 使用 python 构建每个区域中的 EC2 实例列表
- php - 将变量从循环传递到函数
- java - Java - 检索文件,计算,输出到另一个文件?