如何更改ggplot2中PANEL(灰色区域)的纵横比

how to change aspect ratio of the PANEL (grey area) in ggplot2

您好,我正在绘制饼图并将名称放在上面。并且文本被裁剪到面板之外(灰色区域)。

有没有办法改变面板的纵横比?

我试过 theme(aspect.ratio=1.5),但这会将饼图更改为椭圆形。我希望饼图不变,并希望面板更宽。我尝试调整图片的大小,但这并没有改变面板(灰色区域)。

感谢您的帮助。谢谢!

library(ggplot2)
source('PieChart.R')

df = data.frame('Name' = c('long long name one', 'long long name two', 
                           'long long name three', 'long name long four'),
                'Count' = c(10, 20, 30, 40))


png(width=1000, height=600, file='/Users/Yuji/OneDrive/Data/TownState/pie.png')

PieChart(df, 'Name', 'Count')

dev.off()

PieChart.R

PieChart = function (Data1, Name1, Value1){

        position = cumsum(Data1[[Value1]])-0.5*Data1[[Value1]]

        ggplot(data = Data1, aes_string(x=1, y=Value1, fill=Name1)) +

                geom_bar(stat="identity") +
                coord_polar(theta ='y') +
                theme(axis.ticks=element_blank(),
                      axis.title=element_blank(),
                      axis.text.y=element_blank(),
                      axis.text.x=element_text(colour='black'),
                      legend.position='none',
                      # panel.background = element_blank(),
                      panel.grid.major = element_blank(),
                      panel.grid.minor = element_blank(),
                      panel.border = element_blank()#,
                      # aspect.ratio=1.5
                ) +

                scale_y_continuous(breaks=position, labels=Data1[[Name1]])
}

我不确定这是否可能:纵横比必须统一才能使饼图呈圆形。作为解决方法,您可以关闭剪裁并在灰色背景上绘制。

b = ggplotGrob(p + theme(plot.background=element_rect(fill=NA,colour=NA)))
b$layout$clip[b$layout$name=="panel"] = "off"
grid.draw(grobTree(rectGrob(gp=gpar(fill="grey92")), b))

或者,您可以手动编辑 gtable 的 widths/heights。第一步是将面板的空单位替换为 "snpc",这将保持正方形,然后将边距更改为 "null" 单位以尽可能扩大。

library(grid)
library(gtable)

p2 <- p + theme(plot.background=element_rect(fill="grey92"))

g <- ggplotGrob(p2)
g$layout$clip[g$layout$name=="panel"] <- "off"

g$respect <- FALSE

grid.newpage()
g$widths[[4]] <- unit(1,"snpc")
g$heights[[3]] <- unit(1,"snpc")
g$widths[c(1,5)] <- rep(list(unit(1,"null")), 2)
g$heights[c(1,6)] <- rep(list(unit(1,"null")), 2)
grid.draw(g)