r - 如何对齐直方图和箱线图以便它们共享 x 轴?

标签 r tidyverse cowplot

数据

 wages
# A tibble: 1,472 x 3
    wage educ  exper
   <dbl> <fct> <dbl>
 1  7.78 1        23
 2  4.82 1        15
 3 10.6  1        31
 4  7.04 1        32
 5  7.89 1         9
 6  8.20 1        15
 7  8.21 1        26
 8 10.4  1        23
 9 11.0  1        13
10  7.21 1        22
# ... with 1,462 more rows  

对齐直方图和箱线图

我正在尝试使用cowplot包对齐wage列的直方图和箱线图。我希望它们共享 x 轴,但值有点偏离。请参阅下面的表示:

library(tidyverse)
library(cowplot)

wages <- read_csv("http://vincentarelbundock.github.io/Rdatasets/csv/Ecdat/Bwages.csv") %>% 
  select(-X1, -sex) %>% 
  mutate(educ = factor(educ)) 
#> Warning: Missing column names filled in: 'X1' [1]
#> 
#> -- Column specification --------------------------------------------------------
#> cols(
#>   X1 = col_double(),
#>   wage = col_double(),
#>   educ = col_double(),
#>   exper = col_double(),
#>   sex = col_logical()
#> )


p1 <- ggplot(wages) +
  geom_histogram(aes(x = wage)) +
  geom_vline(xintercept = median(wages$wage), color = "red")

p2 <- ggplot(wages) + 
  geom_boxplot(aes(x = wage)) 

plot_grid(p1, p2, ncol = 1, axis = "l", align = 'v')
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

reprex package 于 2021 年 2 月 27 日创建(v1.0.0)

怎样才能让它们完美地共享x轴?

最佳答案

您不仅应该设置限制,还应该设置扩展范围(无)和中断:

p1 <- p1 +
  scale_x_continuous(limits= c(0,50), expand = c(0, 0), breaks = c(0,10,20,30,40,50))
p2 <- p2+
  scale_x_continuous(limits= c(0,50), expand = c(0, 0), breaks = c(0,10,20,30,40,50))

plot_grid(p1, p2, ncol = 1, axis = "l", align = 'v')

enter image description here

关于r - 如何对齐直方图和箱线图以便它们共享 x 轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66404157/

相关文章:

r - 在 ggplot2 中缩小图形时将标签保持在固定距离

r - 使用 collapse R 包按组计算观察值

r - 分组汇总仍然给出每个单独行的结果

r - 使用 plot_grid 更改背景颜色

r - 使用 R 中的 PairViz 包查找欧拉循环 (v 3.0.2)

r - 不断收到错误: Expecting a single value: [extent=2] in summarise

R : readBin and writeBin ( for storing/retrieving MySQL BLOBs or LONGBLOBs )

r - 使用 dplyr 汇总并统计分组 df 中唯一值的数量

r - 如何使cowplot小网格线成为标准ggplot默认软灰色,而不是纯黑色

r - 使用Cowplot时减少地 block 之间的边距