djc55
djc55

Reputation: 555

Adding a legend entry for geom_segment

In the chart below, I would like to include an item in the legend for the blue reference line, which for the sake of this example, we can call "Arbitrary Line". Can anyone provide me a solution for getting that into the legend? Note that the final plot must be rendered in plotly.

enter image description here

library(tidyverse)
library(plotly)

dat <- data.frame(peeps= c("Bill", "Bob", "Becky"),
                  vals = c(10, 15, 12),
                  label = c("8% Fake", "12% Pizza", "45% Becky"),
                  grp = c("Bears", "Bears", "Mongoose") %>% as.factor)
p1 <- dat %>% 
  ggplot(aes(x = peeps, y = vals, fill = grp)) +
  geom_bar(stat = "identity") +
  geom_segment(aes(x = 0.55, xend = 3.45, y = 5, yend = 5), color = "blue") +
  scale_y_continuous(expand = c(0, 0)) +
  coord_flip()

ggplotly(p1) %>% 
  layout(legend = list(orientation = "h",
                       xanchor = "center",
                       y = -0.15,
                       x = 0.5))

Upvotes: 0

Views: 51

Answers (1)

MonJeanJean
MonJeanJean

Reputation: 2906

Try to add:

scale_fill_manual(name = "", values="blue", label="Arbitrary Line")

Upvotes: 2

Related Questions