1

I'm looking to rotate the legend of a plot from vertical lines to horizontal but keep the actual lines vertical in the graph. There are a number of hack type solutions but I think this can now easily be done with ggstance package but I'm not sure how to achieve it.

library(tidyverse) 
library(ggstance)
df <- tibble(x = rnorm(40))
df_stats <-
  df %>%  summarise(
    mean = mean(x), 
    median = median(x)
  ) %>% 
  gather(key = legend, value = value, mean:median)

df %>% 
  ggplot(aes(x = x)) +
  geom_histogram(bins = 20) +
  geom_vline(data = df_stats, aes(xintercept = value, color = legend))

enter image description here

Any suggestions using ggstance? thanks

EDIT per @Allan Cameron comment

As ggstance has been superseded by the latest version of ggplot, I'm happy to see any solution someone might have?

user63230
  • 4,095
  • 21
  • 43
  • 1
    `ggstance` has been superseded by the latest version of ggplot, as explained [here](https://cran.r-project.org/web/packages/ggstance/readme/README.html), so I don't think this is the correct avenue to use. – Allan Cameron Sep 06 '20 at 14:52
  • thanks for the tip. It seems `key_glyph` argument below is all that I needed! – user63230 Sep 06 '20 at 15:05
  • 1
    But `ggstance` was a good pointer, because in its documentation I discovered the `key_glyph` argument :) – starja Sep 06 '20 at 15:10

1 Answers1

6

You need to change the key_glyph argument, see the available key_glyphs. You need "path":

library(tidyverse)
df <- tibble(x = rnorm(40))
df_stats <-
  df %>%  summarise(
    mean = mean(x), 
    median = median(x)
  ) %>% 
  gather(key = legend, value = value, mean:median)

df %>% 
  ggplot(aes(x = x)) +
  geom_histogram(bins = 20) +
  geom_vline(data = df_stats, aes(xintercept = value, color = legend),
             key_glyph = "path")

Created on 2020-09-06 by the reprex package (v0.3.0)

starja
  • 9,887
  • 1
  • 13
  • 28