19

I find out an interesting and strange difference between the same chart in ggplot and ggplotly

income_gap_chart <- ggplot(income_gap, aes(x = Country, y = Percent, fill = Income)) + 
geom_bar(position = "dodge", stat = "identity") +
scale_fill_brewer(palette = "Set1") +
coord_flip() +
theme(axis.title.y = element_blank()) +
scale_y_continuous(limits = c(0, 100)) +
theme_tufte() +
theme(axis.title.y = element_blank()) +
theme(legend.position = "bottom")

For ggplot it looks perfect with a legend title at the bottom

enter image description here

But when I wrap this with ggplotly(), the legend starts to behave differently

enter image description here

My problem - I want the first chart in ggplotly format, but cannot fix this issue and legend at the bottom does not work. Ideas?

Thanks!

micstr
  • 5,080
  • 8
  • 48
  • 76
Anakin Skywalker
  • 2,400
  • 5
  • 35
  • 63

2 Answers2

20

Resolved pretty fast with the help of some R experts.

Added this

ggplotly(income_gap_chart) %>% layout(legend = list(orientation = "h", x = 0.4, y = -0.2))

Result:enter image description here

Thanks!

Anakin Skywalker
  • 2,400
  • 5
  • 35
  • 63
  • 6
    There's no legend title in this solution – pogibas Jan 30 '19 at 23:28
  • @PoGibas, if somebody can add another solution - great! I got the desired result – Anakin Skywalker Jan 30 '19 at 23:31
  • 2
    I get error: `Error in layout(., legend = list(orientation = "h", x = 0.4, y = -0.2)) : unused argument (legend = list(orientation = "h", x = 0.4, y = -0.2))` – PM0087 Jun 25 '20 at 16:29
  • @PeyM87, thanks, sorry for to hear this. I did not touch that code for more than 1 year, so maybe they updated something since then, cannot guarantee for sure it works now. Check the documentation. Thanks! – Anakin Skywalker Jun 25 '20 at 19:14
4

The solution seemed to drop the legend title as pointed out in the comments. This was easy to fix by including title = ... inside layout():

diamonds_chart <- ggplot(diamonds, aes(x = cut, y = carat, fill = color)) + 
  geom_bar(position = "dodge", stat = "identity")
  
diamonds_chart %>% 
  ggplotly %>% 
  layout(
    legend = list(
      orientation = 'h', x = 0.3, y = -0.1, 
      title = list(text = 'My legend title')
      )
    )

enter image description here

hugh-allan
  • 1,170
  • 5
  • 16