图形添加文本-ggfittext

2022-03-29 14:49:54 浏览数 (1)

今天是大年初三,想必小伙伴们都放假在家陪着爸爸妈妈,吃着家乡的饭,和家人一起过节,小编在这里给大家拜个年~祝大家新年新气象,新年好运气有福气,工作顺利,身体健康~

接下来小编向大家介绍一个相对简单的绘图添加文本的R包。

代码语言:javascript复制
install.packages("ggfittext")  #安装包
library(ggfittext)

head(animals)  #查看数据,动物相关数据

1.在box上添加文本

(1)默认参数绘制

代码语言:javascript复制
ggplot(animals, aes(x = type, y = flies, label = animal))  
  geom_tile(fill = "white", colour = "black")  
  geom_fit_text()   #默认参数

(2)改变文字的大小

代码语言:javascript复制
ggplot(animals, aes(x = type, y = flies, label = animal))  
  geom_tile(fill = "white", colour = "black")  

  geom_fit_text(grow = TRUE)   
    #字的大小随数值改变
    # reflow=TRUE ,文字重排以适应格子

(3)改变文字的位置

代码语言:javascript复制
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)默认参数

代码语言:javascript复制
ggplot(altitudes, aes(x = craft, y = altitude, label = altitude))  
  geom_col()  
  geom_bar_text()

(2)修改文本显示方式

代码语言:javascript复制
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)坐标轴转换

代码语言:javascript复制
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坐标

代码语言:javascript复制
head(presidential)  #11个US总统任期等相关数据
代码语言:javascript复制
ggplot(presidential, aes(ymin = start, ymax = end, x = party, label = name))  
  geom_fit_text(grow = TRUE)  
  geom_errorbar(alpha = 0.5)  
  # 添加误差线

0 人点赞