如何删除ggplot2图表中的边距 [英] How to remove margins in ggplot2 chart

查看:42
本文介绍了如何删除ggplot2图表中的边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用ggplot2为乳胶文档创建图,并发现ggplot2增加了许多不必要的边距:

I am currently creating plots with ggplot2 for a latex document and discovered that ggplot2 adds many unwanted margins:

  • plot.background = element_rect(fill ="red")涂成红色:
    • 左边距很小
    • 图片和图例之间的空白很小
    • 左右边距
    • 底部有1px的边距

    还需要哪些规则来消除这些空白?用谷歌搜索所有这些配置选项确实很困难.这是我的实际图表:

    Which more rules are needed to remove these margins? It's really difficult to google all these configuration options. This is my actual chart:

    library(ggplot2)
    library(scales)
    label <- c("A", "B", "C", "D")
    value <- c(61, 26, 9, 4)
    values <- data.frame(label, value)
    myplot <- ggplot(values, aes(x = "", y=value, fill=label))
    myplot <- myplot + theme(legend.position="bottom")
    myplot <- myplot + labs(fill="")
    myplot <- myplot + geom_bar(stat="identity", width=1)
    myplot <- myplot + geom_text(
      aes(x=1.3, y=value/2+c(0, cumsum(value)[-length(value)])),
      label=percent(value/100),
      size=2
    )
    myplot <- myplot + coord_polar(theta="y")
    myplot <- myplot + theme(plot.background=element_rect(fill="red"))
    myplot <- myplot + theme(
      plot.margin=unit(c(0,0,0,0), "mm"),
      legend.margin=unit(0, "mm"),
      axis.title=element_blank(),
      axis.ticks=element_blank()
    )
    ggsave("pie.pdf")
    

    推荐答案

    您可以通过主题元素 axis.text axis.tick.length <删除其余的轴空间./code>.

    You can remove the rest of the axis space via the theme elements axis.text and axis.tick.length.

    因此,您可以在主题代码中添加以下内容:

    So you'd add something like the following to your theme code:

    axis.text = element_blank(), axis.ticks.length = unit(0, "mm")
    

    在ggplot2的当前开发版本 ggplot2_2.1.0.9001 中,有一个新的主题元素 legend.box.spacing 在这里也可能有用,可以将其删除图例与图之间的所有空间: legend.box.spacing = unit(0,"mm").

    In the current development version of ggplot2, ggplot2_2.1.0.9001, there is a new theme element legend.box.spacing that could also be useful here to remove all space between the legend and the plot: legend.box.spacing = unit(0, "mm").

    这篇关于如何删除ggplot2图表中的边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆