这段代码主要用于绘制一个基于数据集'data_draw'的堆积柱状图。具体实现过程如下:

  1. 首先使用ggplot函数创建一个绘图对象p1,并指定x轴变量为'variable',y轴变量为'value',堆积方式为'stack'。

  2. 使用geom_bar函数添加一个堆积柱状图层。其中,填充颜色由'Phylum'变量确定,柱状图的宽度为0.6,填充颜色使用了自定义的调色板'palette'。

  3. 使用scale_fill_manual函数设置填充颜色的手动映射,将其值设置为之前定义的调色板。

  4. 使用labs函数设置坐标轴标签,其中y轴标签为'Relative abundance (%)',x轴标签为'sample'。

  5. 使用theme函数设置整个图形的主题,包括字体、字号、坐标轴标题和文本、图例标题和位置、面板背景、坐标轴线条等。

  6. 最后调用theme_bw函数将整个图形的背景设置为白色,并使用theme函数进一步调整坐标轴刻度线的长度和坐标轴文本的位置。

p1 <- ggplot(data_draw,aes(variable, value),position='stack') +
  geom_bar(aes(fill = Phylum), stat = 'identity',color='black',size=0.4,
           position = 'fill', width = 0.6,data=Phylum.t)+
  scale_fill_manual(values=c(palette))+
  labs(y = 'Relative abundance (%)',x='sample')+
  theme(text=element_text(family='Times New Roman',size=20))+
  theme(
    axis.title=element_text(size=20,face='plain',color='black'),
    axis.text = element_text(size=20,face='plain',color='black'),
    legend.title=element_text(size=20,face='plain',color='black'),
    legend.position = 'right',
    panel.background = element_blank(), 
    axis.line = element_line(colour = 'black', size = 0.4))+theme_bw()+  theme(axis.ticks.length=unit(-0.25, 'cm'), 
        axis.text.x = element_text(margin=unit(c(0.5,0.5,0.5,0.5), 'cm')), 
        axis.text.y = element_text(margin=unit(c(0.5,0.5,0.5,0.5), 'cm')) )

代码解析:

  • ggplot(data_draw,aes(variable, value),position='stack'): 使用ggplot函数创建绘图对象p1,指定数据框为'data_draw',x轴变量为'variable',y轴变量为'value',堆积方式为'stack'。
  • geom_bar(aes(fill = Phylum), stat = 'identity',color='black',size=0.4, position = 'fill', width = 0.6,data=Phylum.t): 添加堆积柱状图层,填充颜色由'Phylum'变量决定,柱状图宽度为0.6,填充颜色使用自定义调色板'palette'。
  • scale_fill_manual(values=c(palette)): 设置填充颜色手动映射,将颜色映射到'palette'调色板。
  • labs(y = 'Relative abundance (%)',x='sample'): 设置坐标轴标签,y轴标签为'Relative abundance (%)',x轴标签为'sample'。
  • theme(text=element_text(family='Times New Roman',size=20)): 设置整体图形主题,字体为'Times New Roman',字号为20。
  • theme(axis.title=element_text(size=20,face='plain',color='black'), axis.text = element_text(size=20,face='plain',color='black'), legend.title=element_text(size=20,face='plain',color='black'), legend.position = 'right', panel.background = element_blank(), axis.line = element_line(colour = 'black', size = 0.4))+theme_bw(): 设置坐标轴标题、文本、图例标题、位置、面板背景、坐标轴线条的样式和颜色,并使用theme_bw()函数将背景设置为白色。
  • theme(axis.ticks.length=unit(-0.25, 'cm'), axis.text.x = element_text(margin=unit(c(0.5,0.5,0.5,0.5), 'cm')), axis.text.y = element_text(margin=unit(c(0.5,0.5,0.5,0.5), 'cm')) ): 调整坐标轴刻度线长度和坐标轴文本位置。

总结: 这段代码使用ggplot2包绘制了基于数据集'data_draw'的堆积柱状图,并通过各种参数设置了图形的样式和主题。通过代码解析,我们可以了解ggplot2包在数据可视化中的强大功能,以及如何使用它来创建美观、清晰的图形。

R语言ggplot2堆积柱状图绘制代码详解

原文地址: https://www.cveoy.top/t/topic/n3rC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录