You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:36:03