##载入所需的R包

library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
## ✓ tibble  3.1.6     ✓ dplyr   1.0.9
## ✓ tidyr   1.2.0     ✓ stringr 1.4.0
## ✓ readr   2.1.1     ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()

##利用cut_width对连续变量进行分箱

smaller <- diamonds %>%
  filter(carat < 3)
ggplot(data = smaller, mapping = aes(x = carat, y = price))+
  geom_boxplot(
    mapping = aes(group = cut_width(carat, 0.1)),#对carat进行分箱,得到每一个宽度都为0.1的分箱
    alpha=0.7,
    color="#1380A1")+
  theme(plot.title = element_text(size = 25, face = "bold"),
        plot.subtitle = element_text(size = 18),axis.title = element_text(size = 16,color = "#222222",face = "bold"),
        axis.ticks = element_blank(),axis.text = element_text(size = 14),
        panel.grid.major.y = element_line(color = "#cbcbcb"), panel.grid.major.x = element_blank(), 
        panel.background = element_blank(), legend.title = element_text(size = 18,face = "bold"))

##利用cut_number对连续变量进行分箱

ggplot(data = smaller, mapping = aes(x = carat, y = price))+
  geom_boxplot(
    mapping = aes(group = cut_number(carat, 20)),#对carat进行分箱,得到宽度与观测数量成正比的分箱
    alpha=0.7,
    color="#1380A1")+
  theme(plot.title = element_text(size = 25, face = "bold"),
        plot.subtitle = element_text(size = 18),axis.title = element_text(size = 16,color = "#222222",face = "bold"),
        axis.ticks = element_blank(),axis.text = element_text(size = 14),
        panel.grid.major.y = element_line(color = "#cbcbcb"), panel.grid.major.x = element_blank(), 
        panel.background = element_blank(), legend.title = element_text(size = 18,face = "bold"))