python - 以不同的方式添加图例和颜色每个条
问题描述
我正在尝试绘制类的分布。
import plotly.graph_objects as go
df = pd.read_csv('https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv')
fig = go.Figure()
fig.add_trace(go.Histogram(histfunc="count", x=df['variety'], showlegend=True))
fig
这给了我:
我希望传说Setosa, Versicolor, Virginica
和每个酒吧都有不同的颜色。
使用熊猫我可以做到(虽然那里的传说有问题):
ax = df['variety'].value_counts().plot(kind="bar")
ax.legend(df.variety.unique())
我希望它与 plotly dash 集成,所以我使用 plotly go。如果有人可以帮助我解决这个问题。这对我很有帮助,因为我是新手。
解决方案
一种解决方案是为品种(或我的数据中的物种)的所有独特值单独添加每个跟踪。添加每个跟踪时,请使用name
参数,以便可以使用适当的文本填充图例。所以像:
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('iris.csv')
var = df.species.unique()
fig = go.Figure()
for v in var:
fig.add_trace(go.Histogram(histfunc="count",
x=df.species[df.species==v],
showlegend=True,
name=v
)
)
fig
推荐阅读
- node.js - 在实时通话期间修改 Twilio statusCallback
- javascript - 将状态值设置为单击按钮的值
- java - #姓名!通过 apache POI 将用户定义的“SpellNumber”函数设置为 excel 单元格时出错
- python - 根据给定坐标从 jpeg 或 tiff 图像创建 LAS 文件
- javascript - 未捕获的引用,数组未在 JavaScript Chrome 控制台中定义
- c - 代码在 DEV C++ 上运行良好,但在 Hacker Rank 的测试用例中出现分段错误
- python - ValueError:未能找到可以处理输入的数据适配器:
, - python - 如何从csv打印出json数据
- html - Angular HTML文件中的下拉列表过滤器
- c# - 用 C# 快速下载 HTML 源代码