#r #tidyverse #cowplot
#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
Выравнивание гистограммы и коробочной диаграммы
Я пытаюсь выровнять гистограмму и wage
диаграмму столбца, используя cowplot
пакет. Я хочу, чтобы они разделяли ось 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`.
Создано 2021-02-27 пакетом reprex (версия v1.0.0)
Как я могу сделать так, чтобы они идеально разделяли ось x?
Ответ №1:
Просто добавляйте xlim(0,50)
к каждому вызову ggplot.
Ответ №2:
Вы должны не только установить ограничения, но также установить расширенный диапазон (значение нет) и разрывы:
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')