如何更改图例的位置

How to change position of legend

我有以下生成散点图的代码,我想更改图例的位置,使其仍在图外但位于中心或中间,我该怎么做?

 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

这是我得到的情节

有几种方法可以做到这一点:

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

有关详细信息,请参阅此内容:https://plotly.com/r/legend/

基本上您只需对您的代码执行此操作:

fig2 <- fig2 %>% layout(xaxis = x, yaxis = y, legend=list(title = list(text='<b> Housing Conditions </b>', orientation = 'h')))

对于垂直方向的默认图例,定位对应于

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

如果你想把它放在 y 方向的底部,使用

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

如果你想让它在 y 方向居中使用

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

如果是水平方向,默认定位是

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

并将图例放在绘图下方的左下角。