更改coord_polar ggplot的半径

AJD*_*AJD 6 r ggplot2 axis-labels pie-chart

我希望相对于该图的其余部分减小ggplot2内置的饼图的显示半径(因为默认设置会切断类别标签)。

以下是一些虚拟数据和代码,这些代码和代码应向您展示我的经历:

library(ggplot2)
library(scales)
library(grid)

Region <- c("North America", "Central America", "South America", "Carribbean",
            "Western Africa", "Northern Africa", "Southern Afica", "Eastern Africa")
Conti <- c(rep("Americas",4), rep("Africa",4))
Freq <- c(runif(8, 1, 100))
Pct <- c(Freq/sum(Freq))
Pos <- c(cumsum(360*Pct)-(360*Pct/2))
Pos <- c(ifelse(Pos<=180,Pos,Pos-180))
df <- data.frame(Region, Conti, Freq, Pct, Pos)

pl <- ggplot(df, aes(x="", y=Freq, fill=Conti)) +
  geom_bar(stat="identity", color="black", width=1) +
  coord_polar(theta='y') +
  guides(fill=guide_legend(override.aes=list(colour=NA))) +
  theme(axis.line = element_blank(),
        axis.ticks=element_blank(),
        axis.title=element_blank(),
        axis.text.y=element_blank(),
        axis.text.x=element_text(color='black', size=18, angle=90-df$Pos),
        panel.background = element_blank(),
        panel.border = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.margin = unit(0, "lines"),
        plot.background = element_rect(fill = "white"),
        plot.margin = unit(c(0, 0, 0, 0), "cm"),
        legend.position = "none") +
  scale_y_continuous(
    breaks=cumsum(df$Freq) - df$Freq/2,
    labels=paste0(df$Region," ",percent(df$Pct)))

print(pl)
Run Code Online (Sandbox Code Playgroud)

如果我减小标签的尺寸,它们相对于馅饼变得难以辨认,如果我增大标签,它们就会被切掉。无论我如何尝试调整aes(),limits,panel.margin等来获得正确的平衡,ggplot2都会自动调整饼图的大小以占据相同的半径。

理想情况下,我想将饼图缩小一半,以便为标签留出更多空间。

我知道这不是最漂亮的情节,但是,我正在更新一个旧图形,因此需要保持格式以进行比较。任何建议,将不胜感激。

AJD*_*AJD 3

几个月后,我发现答案在于对 X 使用数字虚拟值(而不是空值“”),然后向虚拟 x 轴添加大于 x 的限制。代码如下。

然后,问题就变成了调整轴标签以与新半径对齐,因为hjust=vjust=似乎不适用于coord_polar()

为此,我将标签添加为geom_text() 并删除了自动标签。现在这满足了我的需要。

关键的变化在于顶线和底线。

pl <- ggplot(df, aes(x=0.8, y=Freq, fill=Conti)) +
  geom_bar(stat="identity", color="black", width=1) +
  coord_polar(theta='y') +
  geom_text(aes(x=1.65, y=cumsum(df$Freq) - df$Freq/2,
            label=paste0(df$Region," ",percent(df$Pct)),
            angle=90-df$Pos)) +
  guides(fill=guide_legend(override.aes=list(colour=NA))) +
  theme(axis.line = element_blank(),
        axis.ticks=element_blank(),
        axis.title=element_blank(),
        axis.text.y=element_blank(),
        axis.text.x=element_blank(),
        panel.background = element_blank(),
        panel.border = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        plot.background = element_rect(fill = "white"),
        plot.margin = unit(c(0, 0, 0, 0), "cm"),
        legend.position = "none") +
  scale_x_discrete(limits=c(0, 1))

print(pl)
Run Code Online (Sandbox Code Playgroud)