首页 > 解决方案 > Plotly 可视化可以显示颜色、符号、大小等的单独图例吗?

问题描述

像 ggplot2 一样,我们可以为 Plotly Express 可视化提供颜色、符号等单独的图例吗?

from pydataset import data
import plotly.express as px
mtcars = data('mtcars')
mtcars.am = mtcars.am.astype('category')
mtcars.gear = mtcars.gear.astype('category')

plt = px.scatter(mtcars, x = 'mpg', y='qsec', color ='disp', symbol = 'am', size = 'wt')
plt.show()

在这里,不会生成单独的图例。

此外,如果其中一个图例具有连续值条,则其他图例将变得不可见。

在此处输入图像描述

现在,将其与 GGPLOT 进行比较(我使用了 python 包 plotnine):

ggplot(mtcars, aes(x = 'mpg', y='qsec', color ='disp', shape = 'am', size = 'wt')) + geom_point()

在此处输入图像描述

所以,简单而完整。我们如何使用 Plotly 获得这样的输出?

先感谢您。

标签: pythonpython-3.xplotlyplotly-python

解决方案


我认为你最近的尝试看起来很不错。而且我个人认为,只要细节清楚,图例元素的大小就不需要反映图形本身的大小。这里有一个小设置来调整你的legendand colorbar

fig.layout.legend.y = 1.05
fig.layout.legend.x = 1.035
fig.layout.coloraxis.colorbar.y = 0.35

在此处输入图像描述

完整代码:

from pydataset import data
import plotly.express as px
mtcars = data('mtcars')
mtcars.am = mtcars.am.astype('category')
mtcars.gear = mtcars.gear.astype('category')

fig = px.scatter(mtcars, x = 'mpg', y='qsec', color ='disp', symbol = 'am', size = 'wt')

fig.layout.legend.y = 1.05
fig.layout.legend.x = 1.035
fig.layout.coloraxis.colorbar.y = 0.35
fig.show()

推荐阅读