简体   繁体   中英

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. 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.

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. 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))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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