简体   繁体   中英

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

在此处输入图像描述

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

For the default legend with vertical orientation the positioning corresponds to

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

If you want to put it at the bottom in the y-direction use

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

and if you want to have it centered in the y-direction use

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

If 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM