gpt4 book ai didi

r - 更改 coord_polar ggplot 的半径

转载 作者:行者123 更新时间:2023-12-03 18:33:04 24 4
gpt4 key购买 nike

我希望相对于图的其余部分减少 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)

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

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

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

最佳答案

我的建议是使用换行符。

pl <- pl + scale_y_continuous(
breaks=cumsum(df$Freq) - df$Freq/2,
labels=paste0(sapply(strsplit(as.character(df$Region), " "), paste, collapse='\n'),
"\n(", percent(df$Pct), ")"))
ggsave('pie.png', plot=pl, height=15, width=15)

enter image description here

关于r - 更改 coord_polar ggplot 的半径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27373422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com