Reputation: 662
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_rect
as 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))
Upvotes: 6
Views: 3746
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.)
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))
Upvotes: 3
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))
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