首页 > 解决方案 > 以不同的方式添加图例和颜色每个条

问题描述

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

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。如果有人可以帮助我解决这个问题。这对我很有帮助,因为我是新手。

标签: pythonpython-3.xplotlyplotly-dashplotly-python

解决方案


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

在此处输入图像描述


推荐阅读