以不同方式添加图例和颜色

Adding legend and colour each bar differently

我正在尝试绘制 类 的分布图。

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 每个酒吧都有不同的颜色。

使用pandas我可以做到(虽然那里的图例有问题):

ax = df['variety'].value_counts().plot(kind="bar")
ax.legend(df.variety.unique())

我希望它与 plotly dash 集成,所以我正在使用 plotly go。如果有人可以帮助我解决这个问题。这对我来说是一个很大的帮助,因为我是 plotly 的新手。

一个解决方案是为品种(或我的数据中的物种)的所有唯一值单独添加每条轨迹。添加每个轨迹时使用 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