没有坐标轴和网格的ggplot2主题

40

我想绘制一张只包含数据而没有任何其他信息的图表。没有坐标轴、网格线或标题,仅为纯数据图。

但是我总是会得到一些无法去除的额外边距和填充。

library(ggplot2)
library(grid)

theme_bare <- theme(
  axis.line = element_blank(), 
  axis.text.x = element_blank(), 
  axis.text.y = element_blank(),
  axis.ticks = element_blank(), 
  axis.title.x = element_blank(), 
  axis.title.y = element_blank(), 
  #axis.ticks.length = unit(0, "lines"), # Error 
  axis.ticks.margin = unit(c(0,0,0,0), "lines"), 
  legend.position = "none", 
  panel.background = element_rect(fill = "gray"), 
  panel.border = element_blank(), 
  panel.grid.major = element_blank(), 
  panel.grid.minor = element_blank(), 
  panel.margin = unit(c(0,0,0,0), "lines"), 
  plot.background = element_rect(fill = "blue"),
  plot.margin = unit(c(0,0,0,0), "lines")
)

ggplot() + 
  geom_area (data=economics, aes(x = date, y = unemploy), linetype=0) +
  theme_bare

生成这张图片:plot

我想要的是这个:plot ideal

我不知道该如何去掉蓝色并让深灰色贴近边缘。

有人可以给些建议吗?


对于第二部分,您需要为每个轴添加 scale_*_*(expand = c(0,0)) - joran
@joran:所以我尝试添加 + scale_x_continuous(expand = c(0,0)) + scale_y_continuous(expand = c(0,0)),但是无论我使用连续或离散,它都显示“离散值提供给连续比例尺”。 - sharoz
1
提醒一下,将日期设置为数字并应用两个 scale_*_*(expand = c(0,0)) 函数可以去除图表外部的灰色,但对蓝色无效。 - sebastian-c
4个回答

36

以下是仅绘制面板区域的方法:

p <- ggplot() + geom_area (data=economics, aes(x = date, y = unemploy), linetype=0) +
  scale_x_date(expand = c(0,0)) + scale_y_continuous(expand = c(0,0)) +
  theme(line = element_blank(),
        text = element_blank(),
        title = element_blank())

gt <- ggplot_gtable(ggplot_build(p))
ge <- subset(gt$layout, name == "panel")

grid.draw(gt[ge$t:ge$b, ge$l:ge$r])

enter image description here


2
这个可行。谢谢!顺便问一下,哪里可以找到一些文档较少的ggplot函数的最佳信息来源? - sharoz
4
line = element_blank() 真的需要重复两次吗? :-/ - Waldir Leoncio
2
稍微简洁一点,grid::grid.draw(gtable::gtable_filter(ggplotGrob(p), "panel")) - baptiste

32

ggplot2_2.0.0 开始,您可以使用 theme_void

ggplot() + 
  geom_area(data = economics, aes(x = date, y = unemploy), linetype = 0) +
  theme_void()

输入图像描述


1
绘图周围仍有一些空间。 - baptiste
@baptiste 感谢您指出这一点。我关注的是问题中的“_无坐标轴;无网格;无标题;_”部分。 - Henrik
一个小提示,这种方法似乎不能与 ggtext::element_markdown() 一起使用(它会导致 HTML 无法呈现,因此您会在图像上叠加原始 HTML 文本)。 - stevec

10

尝试

last_plot() + theme(axis.ticks.length = unit(0.001, "mm")) + labs(x=NULL, y=NULL)

您可能希望为0刻度长度提交错误报告。


-1

如果你只想要在 theme_bw() 中移除网格线,可以使用以下代码:

+ theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接