如何使用ggplot2绘制Y轴每单位带轮廓线的条形图
R ggplot实现带Y轴单位轮廓的条形图
要实现每个Y轴单位带轮廓线的条形图,只需要先把原数据集按频数拆分为单观测行(1行对应1个Y轴单位高度),绘图时添加轮廓线参数即可。
完整实现代码
方法1:基础R实现(无需额外安装包)
library(ggplot2) # 原数据预处理逻辑 freqtable <- table(iris$Petal.Width) df <- as.data.frame.table(freqtable) colnames(df) = c("Width", "Freq") df$Width = as.numeric(as.character(df$Width)) # 按频数拆分为单观测行,1行对应1个Y轴单位 df_uncount <- df[rep(seq_len(nrow(df)), df$Freq), ] # 绘图:color参数指定轮廓线颜色,linewidth调整线条粗细 ggplot(df_uncount[df_uncount$Width > 2.2, ] , aes(x = Width)) + geom_bar(position = "stack", stat = "count", fill = "tomato2", color = "black", linewidth = 0.3)
方法2:tidyr简化数据处理
如果已经安装tidyr包,可以用uncount函数简化拆分逻辑:
library(ggplot2) library(tidyr) freqtable <- table(iris$Petal.Width) df <- as.data.frame.table(freqtable) colnames(df) = c("Width", "Freq") df$Width = as.numeric(as.character(df$Width)) # 一键按频数拆分 df_uncount <- uncount(df, Freq) ggplot(df_uncount[df_uncount$Width > 2.2, ] , aes(x = Width)) + geom_bar(position = "stack", stat = "count", fill = "tomato2", color = "black", linewidth = 0.3)
参数说明
color:设置单位块轮廓线的颜色,可替换为"white"、"gray"等你需要的颜色linewidth:调整轮廓线的粗细,数值越大线条越粗
内容的提问来源于stack exchange,提问作者Ahdee
相关产品推荐
相关产品推荐

