install.packages("ggfittext") #安装包
library(ggfittext)
head(animals) #查看数据,动物相关数据
1.在box上添加文本
(1)默认参数绘制
ggplot(animals, aes(x = type, y = flies, label = animal)) +
geom_tile(fill = "white", colour = "black") +
geom_fit_text() #默认参数
(2)改变文字的大小
ggplot(animals, aes(x = type, y = flies, label = animal)) +
geom_tile(fill = "white", colour = "black") +
geom_fit_text(grow = TRUE)
#字的大小随数值改变
# reflow=TRUE ,文字重排以适应格子
(3)改变文字的位置
ggplot(animals, aes(x = type, y = flies, label = animal)) +
geom_tile(fill = "white", colour = "black") +
geom_fit_text(place = "topleft", reflow = TRUE)
#topleft文字置于左上
#其他参数topleft, top, topright, right, bottomright, bottom, bottomleft, left,center/middle
2.适用ggplot2的添加文本geom_bar_text()
(1)默认参数
ggplot(altitudes, aes(x = craft, y = altitude, label = altitude)) +
geom_col() +
geom_bar_text()
(2)修改文本显示方式
ggplot(coffees, aes(x = coffee, y = proportion, label = ingredient,
fill = ingredient)) +
geom_col(position = "stack") +
geom_bar_text(position = "stack", grow = TRUE, reflow = TRUE)
#position = "stack",堆叠展示
(3)坐标轴转换
ggplot(coffees, aes(x = coffee, y = proportion, label = ingredient,
fill = ingredient)) +
geom_col(position = "dodge") +
geom_bar_text(position = "dodge", grow = TRUE, reflow = TRUE,
place = "left") +
#position = "dodge" 条形躲避
coord_flip()
#横向转换坐标,把x轴和y轴互换
3. 指定box坐标
head(presidential) #11个US总统任期等相关数据
ggplot(presidential, aes(ymin = start, ymax = end, x = party, label = name)) +
geom_fit_text(grow = TRUE) +
geom_errorbar(alpha = 0.5)
# 添加误差线