【问题标题】:Adding legend and colour each bar differently以不同的方式添加图例和颜色每个条
【发布时间】:2020-06-19 10:32:51
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x plotly plotly-dash plotly-python


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    相关资源
    最近更新 更多