先使用dplyr选取出每类汽车中效率最高的型号。这个问题可以用geom_label()函数,它可以为文本加上方框。可以使用ggrepel包,自动调整标签位置,避免重叠。
options(repos = list(CRAN="http://cran.rstudio.com/"))
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✔ ggplot2 3.3.6 ✔ purrr 0.3.4
## ✔ tibble 3.1.7 ✔ dplyr 1.0.9
## ✔ tidyr 1.2.0 ✔ stringr 1.4.0
## ✔ readr 2.1.2 ✔ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
install.packages("ggrepel")
## 程序包'ggrepel'打开成功,MD5和检查也通过
## Warning: 无法将拆除原来安装的程序包'ggrepel'
## Warning in file.copy(savedcopy, lib, recursive = TRUE): 拷
## 贝D:\R-4.2.0\library\00LOCK\ggrepel\libs\x64\ggrepel.dll到D:
## \R-4.2.0\library\ggrepel\libs\x64\ggrepel.dll时出了问题:Permission denied
## Warning: 回复了'ggrepel'
##
## 下载的二进制程序包在
## C:\Users\86158\AppData\Local\Temp\Rtmp8GjXMe\downloaded_packages里
library(ggrepel)
new <- mpg %>%
group_by(class) %>%
filter(row_number(desc(hwy)) == 1)
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point(aes(colour = class)) +
geom_point(data = new, size = 3, shape = 1) +
geom_label_repel(data =new, aes(label = model))
先使用filter()筛选出每类class最大的hwy值,然后使用geom_point()标记并使用geom_label_repel()对这些点加上标签。
可以对carat进行分箱,然后为每个组生成一个箱线图:
new_carat <- diamonds %>% filter(carat < 3)
ggplot(data = new_carat, aes(x = carat, y = price)) +
geom_boxplot(aes(group = cut_number(carat, 20)))
为了方便呈现,这里筛选除carat大于3的数据,并使用cut_number()将carat划分为20组。
ggplot(data = new_carat, aes(x = carat, y = price)) +
geom_boxplot(aes(group = cut_width(carat, 0.1)))
这里使用cut_width(carat, 0.1)将carat以0.1为间隔划分。