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

如何在子区域居中展示饼图与嵌套饼图,解决饼图显示不全问题

问题原因

  • 饼图上下被截断:默认绘图区域边距过大、可用范围不足,超出边界的饼图和标签内容会被自动裁切
  • 代码运行错误+分类错位:你调用了不存在的sub_data字段生成标签会直接报错;子数据按node排序后和内层父分类的顺序不匹配,会导致内外饼图分类对应错误

修正后可直接运行的代码

library(ggplot2)
library(plotrix)
library(data.table)

df <- structure(list(parent = c("Energy", "Industry", "Transport", "Buildings ", "Agriculture", "Agriculture", "Agriculture", "Agriculture", "Agriculture", "Agriculture", "Agriculture", "Forestry and Land Use " ), node = c("Energy", "Industry", "Transport", "Buildings ", "Enteric Fermentation", "Manure Left on Pasture", "Synthetic Fertilizers", "Paddy Rice", "Manure Management ", "Burning of savannahs", "Other", "Forestry and Land Use "), size = c(35, 21, 14, 6, 4.8, 1.92, 1.56, 1.2, 0.84, 0.6, 1.08, 12)), row.names = c(NA, -12L), class = c("data.table", "data.frame"))  

# 聚合父分类数据,和子分类顺序保持一致
df_data <- aggregate(df$size, by = list(df = df$parent), FUN = sum)
# 先按父分类排序,再按子分类排序,保证内外层分类对应
sub_data <- df[order(factor(df$parent, levels = df_data$df), df$node), ]

df_colors <- c('#85EA72', '#3B3B3F', '#71ACE9', '#747AE6', '#F69852','#F69992')
sub_data_colors <- c('#85EA72', '#3B3B3F', '#71ACE9', '#747AE6', '#F69852','#F69992', '#85EA88', '#3B3B4F', '#71ACC9', '#747EE6', '#F69899','#F68882')

# 修正标签字段:不存在sub_data列,改用node列
sub_data_labels <- paste(sub_data$node, ": ", sub_data$size, "%", sep = "")

center_x <- 0.5
center_y <- 0.5

# 调整绘图边距,避免内容被裁切
par(mar = c(0, 0, 0, 0))
plot.new()
# 设置绘图坐标范围,asp=1保证饼图是正圆形
plot.window(xlim = c(0, 1), ylim = c(0, 1), asp = 1) 

# 绘制外层子分类饼图
sub_data_chart <- floating.pie(
  xpos = center_x,
  ypos = center_y,
  x = sub_data$size,
  radius = 0.35,
  border = "white",
  col = sub_data_colors
)

# 外层标签
pie.labels(
  x = center_x,
  y = center_y,
  angles = sub_data_chart,
  labels = sub_data_labels,
  radius = 0.38,
  bg = NULL,
  cex = 0.8,
  font = 2,
  col = "gray40"
)

# 绘制内层父分类饼图
df_chart <- floating.pie(
  xpos = center_x,
  ypos = center_y,
  x = df_data$x,
  radius = 0.25,
  border = "white",
  col = df_colors
)

# 内层标签
pie.labels(
  x = center_x,
  y = center_y,
  angles = df_chart,
  labels = df_data$df,
  radius = 0.125,
  bg = NULL,
  cex = 0.8,
  font = 2,
  col = "white"
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:48:02