R 中的 ggplot2 包提供了绘制矩形的函数:geom_rect()。
geom_rect()函数可以根据xmin, xmax,ymin, ymax四个点的坐标绘制四边形,这就为我们绘制不等宽柱形图提供了函数基础。
1. 所需数据如下
包含三列数据:
- 第1列是柱子的名字
- 第2列是柱子的宽度
- 第3列是柱子的高度
demo数据可以在这下载https://www.bioladder.cn/shiny/zyp/bioladder2/test/unequalWidthBarPlot/data.txt
2. 不等宽柱形图的具体实现代码如下所示(R语言)
library(tidyverse)
# 读取数据
df = read.delim("https://www.bioladder.cn/shiny/zyp/bioladder2/test/unequalWidthBarPlot/data.txt")
# 处理数据
dfPlot = df %>%
mutate(xmax = cumsum(Width)) %>% # xmax为Width列的累加和
mutate(xmin = xmax - Width) %>% # xmin
mutate(label = (xmin + xmax)/2) # label,xmin和xmax的中间位置,用于标记
# 绘图
ggplot(dfPlot)+
geom_rect(aes(xmin=xmin,xmax=xmax,ymin=0,ymax=Height,fill=Sample), # 利用geom_rect绘制四边形
colour="black",size=0.25)+ # 给四边形添加了个黑色边框
geom_text(aes(x=label,y=Height,label=Height),vjust=-0.5)+ # 添加数字标签
geom_text(aes(x=label,y=0,label=Sample),vjust=1)+ # 添加下方的文字标签
theme_minimal() # 主题