使用element_text在ggplot2中自定义文本

ggplot2的主题系统可以让我们更好的控制图形非数据元素的细节,通过更加精细的修改来提升图像的美感,ggplot2 的主题系统自带多个element_功能

  • element_text( )
  • element_line( )
  • element_rect( )
  • element_blank( )

本节来介绍主题元素element_text() ,使用它控制绘图中文本元素的许多部分,如字体大小、颜色和字体类型。

ggplot2的element_text()剖析

element_text() 控制的元素列表

  • axis.title.x: 自定义 x 轴标签/标题
  • axis.title.y : 自定义 y 轴标签/标题
  • axis.text.x : 自定义 x 轴刻度标签
  • axis.text.y : 自定义 y 轴刻度标签
  • legend.title: 自定义图例标题文本
  • legend.text:自定义图例文本
  • plot.title: 自定义图像主标题
  • plot.subtitle: 自定义图像副标题
  • plot.caption: 自定义图像的脚注
  • plot.tag: 自定义绘图的标签

加载R包

library(tidyverse)
library(palmerpenguins)

依旧还是使用企鹅的数据集,接下来使用element_text() 函数来调整图像的文本元素

p<- penguins %>%
  drop_na() %>%
  ggplot(aes(x=flipper_length_mm,
             y=bill_length_mm, 
             color=species,
             shape=sex))+
  geom_point()+
  labs(title="Palmer Penguins",
       subtitle="Flipper Length vs Bill Length",
       caption="cmdlinetips.com",
       tag = 'A'
  )

p

1. axis.title.*( ):自定义x&y标签文本

通过element_text( )来更改文本,颜色,大小和角度

p + theme(axis.title.x = element_text(size=16, color="purple", 
                                      face="bold",angle=0),
          axis.title.y = element_text(size=16, color="purple", 
                                      face="bold",angle=90))

2. axis.text.*( )自定义x&y刻度文本

p + theme(axis.text.x=element_text(family = "Tahoma",face="bold",
                                   colour="black",size=10),
          axis.text.y = element_text(family = "Tahoma",face="bold",
                                     colour="black",size=10))

3. legend.title( )自定义图例标题文本

p + theme(legend.title=element_text(color="purple",
                                    face="bold",size=12))

4. legend.text( )自定义图例文本

p + theme(legend.text=element_text(face="bold", color="red",size=10))

5. plot.title( ) 自定义主标题

p + theme(plot.title= element_text(size=15,color="blue",hjust = 0.5,
                                   face="bold",family = "Tahoma"))

6. plot.subtitle( )自定义副标题

p + theme(plot.subtitle= element_text(size=13,
                                      color="red",
                                      face="bold"))

7. plot.caption( )自定义脚注

p + theme(plot.caption= element_text(size=12,
                                     color="blue",
                                     face="bold"))

8. plot.tag( )自定义标签

p + theme(plot.tag = element_text(size=16,
                                   color="red",
                                   face="bold"))

喜欢的小伙伴欢迎关注我的公众号

R语言数据分析指南,持续分享数据可视化的经典案例及一些生信知识,希望对大家有所帮助

你可能感兴趣的:(使用element_text在ggplot2中自定义文本)