R 中的 plotly:水平列出图例项并在图下方居中
plotly in R: Listing legend items horizontally and centered below a plot
我一直在 plotly 和 R 中调整图例。我无法弄清楚的一件事是如何(如果可能的话)重新定位图例项,以便它们水平列出并在图下方居中。默认图例项垂直放置并位于图的右侧,如下所示:
plot_ly(data = iris, x = Sepal.Length, y = Petal.Length, mode = "markers", color = Species)
我可以通过以下方式获得下面的图例并以图为中心:
plot_ly(data = iris, x = Sepal.Length, y = Petal.Length, mode = "markers", color = Species) %>% layout(legend = list(x = 0.35, y = -0.5))
但是,我注意到这个图例位置会根据我查看绘图的方式(我制作绘图的尺寸 window 等)而变化。正因为如此,图例有时会不小心与情节重叠(位置太高)或与情节分开一段尴尬的距离(位置太低)。这是图例位置过低的示例图片:
此外,将图例放置在绘图下方时,水平(而不是垂直)列出图例项可能看起来更好。在此示例中,如果在图例中从左到右(而不是从上到下)列出 virginica、versicolor 和 setosa,那就太好了。因此,理想情况下看起来像这样:
是否有可能在水平列出其项目时获得这个 - 即图例位于图的中心和下方(不会改变 window 大小的位置)?
根据 documentation 以下应该可以解决问题:
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
它将图例方向设置为"horizontal",然后将锚点(指向我们指定的位置)设置为图例的中心,然后将其定位在x轴的中间。结果如下图:
我一直在 plotly 和 R 中调整图例。我无法弄清楚的一件事是如何(如果可能的话)重新定位图例项,以便它们水平列出并在图下方居中。默认图例项垂直放置并位于图的右侧,如下所示:
plot_ly(data = iris, x = Sepal.Length, y = Petal.Length, mode = "markers", color = Species)
我可以通过以下方式获得下面的图例并以图为中心:
plot_ly(data = iris, x = Sepal.Length, y = Petal.Length, mode = "markers", color = Species) %>% layout(legend = list(x = 0.35, y = -0.5))
但是,我注意到这个图例位置会根据我查看绘图的方式(我制作绘图的尺寸 window 等)而变化。正因为如此,图例有时会不小心与情节重叠(位置太高)或与情节分开一段尴尬的距离(位置太低)。这是图例位置过低的示例图片:
此外,将图例放置在绘图下方时,水平(而不是垂直)列出图例项可能看起来更好。在此示例中,如果在图例中从左到右(而不是从上到下)列出 virginica、versicolor 和 setosa,那就太好了。因此,理想情况下看起来像这样:
是否有可能在水平列出其项目时获得这个 - 即图例位于图的中心和下方(不会改变 window 大小的位置)?
根据 documentation 以下应该可以解决问题:
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
它将图例方向设置为"horizontal",然后将锚点(指向我们指定的位置)设置为图例的中心,然后将其定位在x轴的中间。结果如下图: