Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in legend position between ggplot and ggplotly?

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!

like image 385
Anakin Skywalker Avatar asked Jan 30 '19 23:01

Anakin Skywalker


People also ask

How do you set the position of a legend in R?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

What is the difference between ggplot2 and Plotly?

Aesthetically, many users consider ggplot2 to be better looking than Plotly, due to its margins and points. In terms of speed, ggplot2 tends to run much slower than Plotly. With regard to integration, both Plotly and ggplot2 can integrate with a variety of tools, like Python, MATLAB, Jupyter, and React.


1 Answers

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!

like image 112
Anakin Skywalker Avatar answered Sep 20 '22 05:09

Anakin Skywalker