Skip to content

geom_vline messes up geom_line legend, if show_guide = TRUE #1267

Closed
@maxheld83

Description

@maxheld83

Let's say I have some line graph via geom_line and would like to add some geom_vlines as thresholds.
Let's further say that I have several such geom_vlines and would therefore require a legend.

Here's the base layer plot:

library(ggplot2)
data(mpg)

# base plot
g <- ggplot()
g <- g + geom_line(data = mpg, mapping = aes(y = cty, x = year, color = manufacturer), stat = "summary", fun.y = mean)
g

So far, so good:

baseplot


Now let's try and add the threshold via geom_hline with a custom legend:

# add threshold via geom_hline()
g + geom_vline(aes(xintercept = 2004, linetype = "Funny Law"), show_guide = TRUE) + scale_linetype_manual(values = c("Funny Law" = "dashed"))  # screws up all geom_line legends

Not so great, the base-layer legends are all screwed up:

geomhline


Ok, let's see whether we can make this work via geom_linerange() with separate dataframes:

thresholds <- data.frame(threshold = "Funny Law", year = 2004, ymin = 0, ymax = 35)
g + geom_linerange(data = thresholds, mapping = aes(x = year, ymin = ymin, ymax = ymax, linetype = threshold))  # works ok

Works ok, except that the geom_linerange doesn't fill the entire y-height of the plot, but ok:

linerange


Then wouldn't we expect the same approach to work via geom_vline() with a separate dataframe?

# add threshold via geom_hline() WITH separate data
g + geom_vline(data = thresholds, mapping = aes(xintercept = year, linetype = threshold), show_guide = TRUE)  # screws up all geom_line legends

Nope, the same problem with screwed up legends returns:

vlinesep


Bug or my mistake?


May be related:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions