2

I have the following code producing a scatter plot and I would like to change the position of the legend so that is still outside the plot but in the center or middle, how could I do that?

 f <- list(
   family = "Courier New, monospace",
   size = 18,
   color = "#7f7f7f"
  )
 x <- list(
   title = "Age of Buildings",
   titlefont = f,
   zeroline = FALSE,
   showline = FALSE,
   showticklabels = TRUE,
   showgrid = TRUE
  )
  y <- list(
    title = "Total Violations",
    titlefont = f,
    zeroline = FALSE,
    showline = FALSE,
    showticklabels = TRUE,
    showgrid = TRUE
   )
fig2 <- plot_ly(final, x=~agebuilding, y=~violationstotal, mode= "markers", color = ~INdexrehabless6, size = ~totalvalue)
fig2 <- fig2 %>% layout(xaxis = x, yaxis = y, legend=list(title=list(text='<b> Housing Conditions </b>'))) #chaging name legend
fig2

Here is the plot I get

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
Pierre
  • 151
  • 1
  • 8

2 Answers2

3

For the a legend with vertical orientation

  • the default positioning corresponds to

    layout(legend = list(orientation = "v", y = 1, x = 1))

    and puts the legend in the top right corner of the plot.

  • to put it at the bottom in the y-direction use

    layout(legend = list(orientation = "v", y = 0, x = 1))

  • to have it centered in the y-direction use

    layout(legend = list(orientation = "v", y = .5, x = 1))

In case of a horizontal orientation

  • the default positioning is

    layout(legend = list(orientation = "h", y = -.1, x = 0))

    and puts the legend in the lower left corner beneath the plot.

  • to put it at the top in the y-direction use

    layout(legend = list(orientation = "v", y = 1.1, x = 0))

stefan
  • 90,330
  • 6
  • 25
  • 51
1

Theres a few ways to do this:

fig2 <- fig2 + layout(legend = list(x = 0.1, y = 0.9)) #puts it on the plot, mess with x and y numbers


fig2 <- fig2 + layout(legend = list(orientation = 'h')) #puts it on the below the plot

See this for more info: https://plotly.com/r/legend/

Basically you'd just do this to your code:

fig2 <- fig2 %>% layout(xaxis = x, yaxis = y, legend=list(title = list(text='<b> Housing Conditions </b>', orientation = 'h')))
Angela C
  • 146
  • 1
  • 9
  • and do you know how may I change the fonts and size of the legend? as you can see I was able to do that for the x and y axis. – Pierre Apr 15 '20 at 20:32
  • is there any way that in horizontal legends, the title to be placed above the legends? something like the following link but in plotly https://stackoverflow.com/questions/32656553/plot-legend-below-the-graphs-and-legend-title-above-the-legend-in-ggplot2 – Abbas Nov 29 '22 at 12:58