简体   繁体   English

在 ggplot2 中的 plot 区域外添加水平线

[英]Add horizontal lines outside plot area in ggplot2

I've tried finding an answer but nothing seems to work.我试过找到答案,但似乎没有任何效果。 The first image below is a scatterplot drawn in ggplot2, which has been post-processed by a specific LaTeX journal template on Overleaf.下面的第一张图是在 ggplot2 中绘制的散点图,经过 Overleaf 上特定的 LaTeX 期刊模板后处理。 I would like to re-create the chart without having to use the template.我想重新创建图表而不必使用模板。

Unfortunately, I haven't been able to figure out how to draw the horizontal lines that separate the title area, and note area (respectively) from the main plot region (see red arrows.不幸的是,我无法弄清楚如何绘制将标题区域和注释区域(分别)与主要 plot 区域分开的水平线(参见红色箭头。

How can I do this?我怎样才能做到这一点?

Oh, the second image is the one that is produced from the code below.哦,第二张图片是由下面的代码生成的。

Thanks!谢谢!

library(ggplot2)
theme_set(theme_bw())  # pre-set the bw theme.
data("midwest", package = "ggplot2")


# Scatterplot
gg <- ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state, size=popdensity)) + 
  geom_smooth(method="loess", se=F) + 
  xlim(c(0, 0.1)) + 
  ylim(c(0, 500000)) + 
  labs(y="Population", 
       x="Area", 
       title="Figure 4: Scatterplot", 
       caption = "Source: midwest") +
  theme(plot.background = element_rect(colour="black",size=1))

plot(gg)

在此处输入图像描述

在此处输入图像描述

You can set coord_cartesian(clip = "off") and add a couple of annotation_custom calls.您可以设置coord_cartesian(clip = "off")并添加几个annotation_custom调用。 This allows plotting relative to the panel without having to specify co-ordinates relative to your data:这允许相对于面板进行绘图,而无需指定相对于数据的坐标:

ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state, size=popdensity)) + 
  geom_smooth(method="loess", se=F) + 
  xlim(c(0, 0.1)) + 
  ylim(c(0, 500000)) + 
  labs(y="Population", 
       x="Area", 
       title="FIGURE 4: Scatterplot", 
       caption = "Source: midwest") +
  coord_cartesian(clip = "off") +
  annotation_custom(grid::linesGrob(x = c(-0.12, 1.19), y = c(1.03, 1.03))) +
  annotation_custom(grid::linesGrob(x = c(-0.12, 1.19), y = c(-.07, -.07))) +
  theme(plot.background = element_rect(colour="black", size = 1),
        plot.title = element_text(size = 16, face = 2, vjust = 5, hjust = -0.2),
        plot.margin = margin(20, 20, 20, 20))

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM