Scott
Scott

Reputation: 662

How to add line at top panel border of ggplot2

I would like to be able to programmatically assign a green line to the very top of my plot.

Below I demonstrate in an example what I would like, except the line is at the very bottom, instead of the top. Ideally, I would accomplish this in theme in a similar way.

I have tried to accomplish the top line myself with panel.border but it takes a element_rectas a parameter meaning that the other sides of the plot will also get the green line.

While it is preferable to use theme, I am open to using geom_hline or anything else. When trying to implement a solution with geom_hline I ran into trouble identifying the max value of the y axis as calculated by ggplot to cleanly put the line in the same place regardless of the scale changing from plot to plot. With my real data, the scale of the y axis varies widely and has different units of measurement from plot to plot.

 library(tidyverse)
 data(mtcars)

 mtcars %>% 
     ggplot(aes(x= mpg, y= disp)) +
     geom_point() +
     theme(axis.line.x= element_line("green", size= 2))

greenline

Upvotes: 6

Views: 3746

Answers (2)

r2evans
r2evans

Reputation: 160952

A relatively newer feature in ggplot2 is the use of a secondary axis, which solves this a little more directly (and, imo, elegantly):

gg <- mtcars %>% 
  ggplot(aes(x= mpg, y= disp)) +
  geom_point() +
  theme(axis.line.x= element_line("green", size= 2))

gg + scale_x_continuous(sec.axis=sec_axis(~., breaks = NULL))
# Warning in min(x) : no non-missing arguments to min; returning Inf
# Warning in max(x) : no non-missing arguments to max; returning -Inf
# Warning in min(x) : no non-missing arguments to min; returning Inf
# Warning in max(x) : no non-missing arguments to max; returning -Inf

(I have not figured out how to prevent the warnings without affecting the primary axis too.)

ggplot with upper line

If you want axis ticks (albeit no labels), you can get rid of the warnings:

gg + scale_x_continuous(sec.axis=sec_axis(~., labels = NULL))

ggplot with upper line with axis ticks, no warnings

Upvotes: 3

jdobres
jdobres

Reputation: 11957

You could accomplish this with annotate and clever use of Inf values. Note that because annotate is drawing inside the plot and not on the axis line outside of it, you need a line of double thickness to match what you did with theme. The use of Inf values guarantees that the line will be placed at the top of the plot regardless of the scale of its units.

library(tidyverse)
data(mtcars)

mtcars %>% 
  ggplot(aes(x= mpg, y= disp)) +
  geom_point() +
  annotate(geom = 'segment', y = Inf, yend = Inf, color = 'green', x = -Inf, xend = Inf, size = 4) +
  theme(axis.line.x= element_line("green", size= 2))

enter image description here

Further, you could save the call to annotate in a variable and then simply add this to plots later, if you wanted to assign the line programmatically.

Upvotes: 7

Related Questions