【问题标题】:Align a piechart in plot area在绘图区域中对齐饼图
【发布时间】:2017-12-06 23:13:47
【问题描述】:

我正在生成一个饼图,我想将它合并到一个闪亮的页面中。绘图区域(即:绘图周围的空白区域)将是流动的。我希望绘图本身(灰色区域和饼图)与绘图区域的左侧对齐,而不是居中显示。有什么想法吗?

ggplot(treeData, aes(x = "", fill = ClassName)) +
  ggtitle("Species distribution") + 
  geom_bar(width = 1) + 
  coord_polar("y", start=0) +
  xlab("") + ylab("") +
  theme(
    axis.text.x=element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid  = element_blank(),
    plot.margin=unit(c(25,0,0,0), "pt")) +
  scale_fill_manual(values= c("#ffff00", "#008080", "#00ff00"))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    here. 提供了有关此答案为何有效的更详细说明,简而言之,您需要将绘图放置在一个网格中,该网格可以随着您调整封闭图像的大小而扩展。

    library(ggplot2)
    library(grid)
    library(gtable)
    
    # some test data
    animals <- as.data.frame(
      table(Species =
              c(rep("Moose", sample(1:100, 1)),
                rep("Frog", sample(1:100, 1)),
                rep("Dragonfly", sample(1:100, 1))
              )))
    
    # make the pie chart
    g <- ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
      geom_bar(width = 1, stat = "identity") +
      coord_polar("y", start=0) +
      theme(
        axis.text.x=element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid = element_blank(),
        plot.margin=unit(c(25,0,0,0), "pt"))
    
    # set the desired width and height of the
    # pie chart (need to play around to find 
    # numbers that work
    plotwidth = unit(6.1, "inch")
    plotheight = unit(5, "inch")
    
    # place into matrix that can expand
    grob <- ggplotGrob(g)
    mat <- matrix(list(grob, nullGrob(), nullGrob(), nullGrob()), nrow = 2)
    widths <- unit(c(1, 1), "null")
    widths[1] <- plotwidth
    heights <- unit(c(1, 1), "null")
    heights[1] <- plotheight
    gm <- gtable_matrix(NULL, mat, widths, heights)
    grid.newpage()
    grid.draw(gm)
    

    【讨论】:

      【解决方案2】:

      您可以尝试通过添加来更改边距

      theme(plot.margin = unit(c(5.5, 100, 5.5, -100), "points"))
      

      或者使用cowplot函数

      cowplot::plot_grid(your_plot, NULL, ncol=2, rel_widths = c(2,1))
      

      【讨论】:

      • 谢谢,但我真正要找的是如何在区域内对齐绘图,而不是调整边距
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多