Pierre
Pierre

Reputation: 161

How to change position of legend

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

Upvotes: 2

Views: 1866

Answers (2)

stefan
stefan

Reputation: 125697

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))

Upvotes: 3

Angela C
Angela C

Reputation: 176

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')))

Upvotes: 1

Related Questions