30

I have been tweaking legends in plotly and R. One thing I am unable to figure out is how (if it is possible) to reposition legend items so that they are listed horizontally and centered below the plot. The default legend items are positioned vertically and located to the right of the plot, as shown here:

plot_ly(data = iris, x = Sepal.Length, y = Petal.Length, mode = "markers", color = Species)

I am able to get the legend below and centered to the plot by the following:

plot_ly(data = iris, x = Sepal.Length, y = Petal.Length, mode = "markers", color = Species) %>% layout(legend = list(x = 0.35, y = -0.5))

However, I notice that this legend position changes based on how I view the plot (the dimensions I make the plot window, etc). Because of this, the legend will sometimes accidentally overlap the plot (by being positioned too high up) or be separated from the plot by an awkwardly-large distance (by being positioned too low). Here is an example image of the legend being positioned too low:

Legend moves depending on plot window dimensions

Moreover, when placing the legend below the plot, it may look better to have legend items listed horizontally (instead of vertically). In this example, it would be great to have virginica, versicolor, and setosa listed left to right in the legend (instead of top to bottom). Hence, ideally looking like this:

Ideal

Is it possible to obtain this - that is, a legend positioned centered and below the plot (that does not change location with window size) while listing its items horizontally?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158

1 Answers1

68

According to documentation the following should do the trick:

data(iris)
plot_ly(data = iris, 
        x = ~Sepal.Length, 
        y = ~Petal.Length, 
        mode = "markers", 
        color = ~Species) %>%
layout(legend = list(orientation = "h",   # show entries horizontally
                     xanchor = "center",  # use center of legend as anchor
                     x = 0.5))             # put legend in center of x-axis

It sets the legend orientation to "horizontal", then sets the anchor (point which position we specify) to the center of the legend, and then positions it in the middle of the x-axis. Which results in the following graph:

enter image description here

Nick To
  • 848
  • 8
  • 9
  • Thanks! There is a little overlaping between the x axis label and the legend with some zoom level: any idea how to manage the space between them? – yeahman269 Aug 26 '20 at 11:59
  • 7
    Adding `y=-0.2` to the `legend=list()` should drop the legend below the x-axis label. Adjust the value to get desired fit. – TTS Mar 30 '21 at 13:16
  • I confirm @TTS. Setting `y` to a negative value such as `-0.2` or `-0.3` does the trick. Thanks. – Stéphane Laurent Jul 20 '21 at 18:11
  • 2
    Would it be possible to vertical align it under the title (without having to guess the y value?) – ccamara Dec 08 '21 at 12:53