Plotly 可视化可以显示颜色、符号、大小等的单独图例吗?

Can a Plotly visualization show separate Legends for Color, Symbol, Size, etc.?

像 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 获得这样的输出?

提前谢谢你。

我觉得你最近的尝试看起来不错。而且我个人认为,只要细节清楚,图例元素的大小就不需要反映图形本身的大小。这是调整 legendcolorbar:

的一些设置
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()