python - 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 获得这样的输出?
先感谢您。
解决方案
我认为你最近的尝试看起来很不错。而且我个人认为,只要细节清楚,图例元素的大小就不需要反映图形本身的大小。这里有一个小设置来调整你的legend
and 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()
推荐阅读
- vba - Excel VBA 用户窗体 - 最小化按钮
- vba - Excel VBA 自动工作表创建器
- angularjs - AngularJS / HAML:如果属性为真,则添加 CSS 类
- vue.js - 一页多次使用Vue组件的正确方法
- javascript - 文本超出 div (CSS)
- html - Libgdx ClassReflection.newInstance 不适用于 html 版本
- php - 了解致命错误:无法在写入上下文中使用临时表达式
- unix - 如何以编程方式确定哪个是 Solaris/illumos 上的引导盘?
- git - 如何从特定分支中完全删除 GitHub 的最后两个提交
- javascript - 测试 $mdDialog resolve 是否调用了正确的服务