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

如何使用ggplot绘制3D堆叠条形图?附示例数据集

用ggplot绘制3D堆叠条形图

我有如下数据集:

Name <- c("Present", "Extra", "Updated")
Gyor <- c(94143, 13691,12661)
Agglomeration <- c(58462, 20669, 6613)
df <- data.frame(Name, Gyor, Agglomeration)
print(df)

希望用ggplot绘制一张类似3D堆叠条形图(示例为立体视角下的分组堆叠条形,呈现出深度效果)的图形。


解决方案

ggplot2本身没有原生3D图形支持,以下提供两种实现思路:

1. 数据预处理(转长格式)

ggplot对长格式数据兼容性更好,先转换数据结构:

# 加载依赖包
library(ggplot2)
library(tidyr)

# 转换为长格式
df_long <- pivot_longer(df, cols = -Name, names_to = "Region", values_to = "Value")

2. 伪3D堆叠条形图(推荐)

通过视觉偏移和阴影模拟3D效果,避免真3D的数据失真问题:

ggplot(df_long, aes(x = Name, y = Value, fill = Region)) +
  # 主堆叠条形
  geom_bar(stat = "identity", position = "stack", width = 0.7, color = "gray30") +
  # 叠加小一号条形模拟立体侧面
  geom_bar(stat = "identity", position = "stack", width = 0.6, color = "gray30",
           aes(y = Value - 5000), fill = "gray80") +
  # 自定义配色贴近示例风格
  scale_fill_manual(values = c("#2c7fb8", "#7fcdbb")) +
  # 主题调整增强立体观感
  theme_minimal() +
  theme(
    panel.grid = element_blank(),
    axis.text.x = element_text(angle = 45, hjust = 1),
    plot.title = element_text(hjust = 0.5)
  ) +
  labs(title = "3D堆叠条形图模拟", x = "类别", y = "数值")

3. 真3D效果(可选)

使用gg3D包实现真实立体视角,注意此方式可能影响数据准确性:

# 首次使用需安装包
# install.packages("gg3D")
library(gg3D)

ggplot(df_long, aes(x = Name, y = Value, z = as.integer(factor(Region)), fill = Region)) +
  geom_bar_3D(stat = "identity", position = "stack") +
  scale_fill_manual(values = c("#2c7fb8", "#7fcdbb")) +
  theme_void() +
  labs(title = "真3D堆叠条形图") +
  coord_3D(theta = 30, phi = 30)

内容的提问来源于stack exchange,提问作者Attila Borsos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:07:37