首页 > 解决方案 > 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

simple cars plot

Modded version

enter image description here

标签: rggplot2data-visualization

解决方案


我对此非常好奇,但发现我的首选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 日创建。


推荐阅读