首页 > 解决方案 > 如何使用ggplot制作内部边框

问题描述

我正在做一个环形图,ggplot我想为类别添加边框,但它们重叠。有没有办法让矩形内部的边框?

可重现的例子。
数据:

plot.df <- data.frame("number"=c(3455, 3714, 2345), 
                      "group"=c("A","B", "C"))
plot.df$fraction <- plot.df$number / sum(plot.df$number)
plot.df <- plot.df[order(plot.df$fraction), ]
plot.df$ymax <- cumsum(plot.df$fraction)
plot.df$ymin = c(0, head(plot.df$ymax, n=-1))

阴谋:

ggplot(plot.df, aes(color = group, fill=group, 
                    ymax=ymax, ymin=ymin, 
                    xmax=4, xmin=2.5)) +
  geom_rect(alpha = 0.6, size = 4) +
  coord_polar(theta="y")  +
  xlim(c(0, 4)) +
  theme_bw() +
  theme(panel.grid=element_blank(), axis.text=element_blank()) +
  theme(axis.ticks=element_blank()) +
  labs(title="My Ring Plot", x = "", y = "", 
       fill = "", color = "") +
  theme(plot.title = element_text(hjust = 0.5))

我得到以下情节,除了边界之外,这是正确的。

环形图

例如,在 B 和 C 之间,只有 B(绿色)边框是可见的,我希望在粗蓝线旁边看到一条粗绿线。我自己解释了吗?

谢谢你的帮助!

编辑:

我找到了一个肮脏的解决方案,它并不完美或优雅,但它确实可以完成工作。

首先我们需要修改 ymin 列

plot.df$ymin = c(0.0125, head(plot.df$ymax, n=-1)+ 0.0125)

然后为“幽灵”类别添加一个新行

plot.df <- rbind(c(234, "D", 0.0125, 0.0125, 0), plot.df)
plot.df[,4] <- as.numeric(plot.df[,4])
plot.df[,5] <- as.numeric(plot.df[,5])

现在我们可以让情节隐藏“幽灵”类别

ggplot(plot.df, aes(color = group, fill=group,
                    ymax=ymax, ymin=ymin,
                    xmax=4, xmin=3)) +
  geom_rect(alpha = 0.6, size = 4) +
  coord_polar(theta="y")  +
  xlim(c(0, 4)) +
  theme_bw() +
  scale_fill_manual(breaks = c("A", "B", "C"),
                    values = c("red", "green", "blue", "white"),
                    aesthetics = c("colour", "fill")) +
  theme(panel.grid=element_blank(), axis.text=element_blank()) +
  theme(axis.ticks=element_blank()) +
  labs(title="My Ring Plot", x = "", y = "",
       fill = "", color = "") +
  theme(plot.title = element_text(hjust = 0.5))

环形图 2

这看起来像我正在寻找的东西,但我制作它的方式并不理想。

还有其他解决方案来实现这一目标吗?谢谢!

标签: rggplot2

解决方案


推荐阅读