r - 如何使用 R (ggplot2) 分解圆环图切片

标签 r ggplot2 donut-chart exploded

左边是我的圆环图当前的样子,右边是它应该的样子:

enter image description here

有没有办法使用 R 来分解圆环图?

这是我的代码:

ggplot(dat, aes(fill = goalGroups, ymax = ymax, ymin = ymin, xmax = 4.8, xmin = 3)) +
  geom_rect(color = "white") +
  coord_polar(theta="y", direction = -1) +
  xlim(c(0, 8)) +
  theme_bw() +
  theme(panel.grid=element_blank()) +
  theme(axis.text=element_blank()) +
  theme(axis.ticks=element_blank()) +
  theme(axis.title.x = element_blank()) +
  theme(axis.title.y = element_blank()) +
  theme(panel.border = element_blank())

非常感谢您的帮助!

最佳答案

您可以尝试为每个类别创建 xlimylim

例如

数据

dat = data.frame(count=c(30,  10), category=c("A",  "C"),stringsAsFactors = F)

额外计算

dat$fraction = dat$count / sum(dat$count)
dat = dat[order(dat$fraction), ]
dat$ymax = cumsum(dat$fraction)-0.01
dat$ymin = c(0, head(dat$ymax, n=-1))+0.01
dat$all_=length(unique(dat$category))
dat$x1=dat$all_-(1:nrow(dat))*0.5+1
dat$x2=dat$all_-(1:nrow(dat))*0.5+2

情节

p2=ggplot()+aes(ymin=0)+geom_rect(data=dat,aes(fill=category,ymax=ymax, ymin=ymin,  xmax=x1, xmin=x2),color = "white")+
  ylim(0,1)+
  xlim(c(0,3+length(unique(dat$category))))+
  coord_polar(theta="y", direction = -1) +
  theme_bw() +
  theme(panel.grid=element_blank()) +
  theme(axis.text=element_blank()) +
  theme(axis.ticks=element_blank()) +
  theme(axis.title.x = element_blank()) +
  theme(axis.title.y = element_blank()) +
  theme(panel.border = element_blank())
p2

enter image description here

也适用于两个以上的类别

dat = data.frame(count=c(30,15,  10), category=c("A", "B", "C"),stringsAsFactors = F)

enter image description here

关于r - 如何使用 R (ggplot2) 分解圆环图切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35175606/

相关文章:

r - 在 r 中创建特定长度和字符的向量

R使用来自单独数据框的日期查询一个数据框中的日期

r - ggplot 将文本添加到 R 中圆环图的中心

d3.js 标题上方具有固定纵横比的响应式图表

r - 通过独特的组合扩展数据框并计算它们的平均值

R在对称矩阵中用零替换矩阵元素的更好方法

r - 我如何切割 `geom_curve` 绘制的曲线,以免它们与 `geom_text` 中 `ggplot2` 绘制的标签重叠?

r - 更改 ggplot 中图例形状的填充

r - ggpubr:更改 stat_compare_means Kruskal-Wallis p 值的字体大小

javascript - 为什么我用 Chart.js 创建的圆环图没有出现?