3

I want to add a line on the top and bottom of my plots (bottom line below the x label and axis) created using ggplot2. So far I have added a rectangle around the plot, but I do not want the lines on the sides.

x <- 1:10
y <- rnorm(10,mean = x)
df <- data.frame(x,y)
library(ggplot2)
ggplot(data = df, mapping = aes(x,y)) + geom_point() +
  theme(plot.background = element_rect(size = 1, color = 'blue'))

I hope you guys have a solution.

pogibas
  • 27,303
  • 19
  • 84
  • 117
Markus
  • 33
  • 3

3 Answers3

1

Will something similar to this work?

x <- 1:10
y <- rnorm(10,mean = x)
df <- data.frame(x,y)
ggplot(data = df, mapping = aes(x,y)) + geom_point() +
    annotate(geom = 'segment', 
             y = Inf, 
             yend = Inf, 
             x = -Inf, 
             xend = Inf, 
             size = 2) +
    theme(axis.line.x = element_line(size = 1))

enter image description here

forestfanjoe
  • 412
  • 4
  • 11
0

Not a perfect, but working solution. You have to plot huge "-" (size = 1000) outside plot area. This solution is not perfect as you have to manually adjust position of "-" on the y-axis.

df <- data.frame(x = 1:10, y = 1:10)
library(ggplot2)
ggplot(df, aes(x, y)) + 
    geom_point() +
    # Y position adjusted manually
    geom_text(aes(5, 2.9, label = "-"), color = "blue", size = 1000)  +
    # Y position adjusted manually
    geom_text(aes(5, 21.2, label = "-"), color = "blue", size = 1000)  +
    # Plot outside plot area
    coord_cartesian(ylim = c(0, 10), clip = "off")

enter image description here

pogibas
  • 27,303
  • 19
  • 84
  • 117
0

I am not completely happy with the solution as I don't fully grasp

  • how to change the size of the lines
  • why they are not perfectly aligned with top and bottom when using patchwork::wrap_plots()
  • why it does not show the top line using ggpubr::ggarrange() or cowplot::plot_grid()

but based on this code, I suggest the following solution:

library(ggplot2)
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(data = df) + aes(x, y) + geom_point() 

top_line <- grid::grobTree(grid::linesGrob(x = grid::unit(c(0, 1), "npc"), y = grid::unit(1, "npc")))
bot_line <- grid::grobTree(grid::linesGrob(x = grid::unit(c(0, 1), "npc"), y = grid::unit(0, "npc")))

patchwork::wrap_plots(top_line, p, bot_line,
                      ncol = 1, nrow = 3,
                      heights = c(0, 1, 0))

ggpubr::ggarrange(top_line, p, bot_line,
                  ncol = 1, nrow = 3,
                  heights = c(0, 1, 0))

cowplot::plot_grid(top_line, p, bot_line,
                   ncol = 1, nrow = 3,
                   rel_heights = c(0, 1, 0))

Created on 2022-08-25 with reprex v2.0.2

Paul Schmidt
  • 1,072
  • 10
  • 23