首页 > 解决方案 > 在其透明背景上居中饼图

问题描述

此代码生成的图表不会将图表放置在输出文件透明背景的中心/中间。有没有办法调整代码使圆最终居中?我一直在摆弄不同的主题元素,但无济于事。谢谢。

馅饼

library(ggplot2)

# sample data
df <- data.frame(group = factor(c("A", "B", "C")), y = c(20,30,50))

# plot code
pie <- ggplot(df, aes(x="", y= y, fill=group))+
  geom_bar(width = 1, stat = "identity", show.legend = FALSE)+
  xlab("")+
  ylab("")+
  coord_polar("y", start=0)+
  theme_minimal()+
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid  = element_blank())

# save as png with transparent background
ggsave(filename= "pie.png",
       plot= pie,
       device = "png",
       type = "cairo-png",  
       bg = "transparent",
       width = 2, 
       height = 2, 
       units = "cm", 
       dpi = 800)

标签: rggplot2

解决方案


您可以gtable_filtergtable包中使用仅提取绘图面板:

library(gtable)
pie <- ggplot(df, aes(x="", y= y, fill=group))+
  geom_bar(width = 1, stat = "identity", show.legend = FALSE)+
  xlab("")+
  ylab("")+
  coord_polar("y", start=0)+
  expand_limits(y = 0) +
  theme_minimal()+
  theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid  = element_blank())

pie <- ggplotGrob(pie)
pie <- gtable::gtable_filter(pie, "panel") 

ggsave(filename= "pie.png",
       plot= pie,
       device = "png",
       bg = "transparent",
       width = 2, 
       height = 2, 
       units = "cm", 
       dpi = 800)

在此处输入图像描述


推荐阅读