【问题标题】:Set Plotly Bar Color Based on 3rd Column Value in Python根据 Python 中的第三列值设置绘图条颜色
【发布时间】:2021-03-12 16:19:12
【问题描述】:

我有以下名为 data 的数据框:

+----+----------+-----------+---------+
|    |    COUNT | City      | Go_NoGo |
|----+----------+-----------+---------|
|  1 |        1 | Maimi     | False   |
|  3 |      570 | Chicago   | False   |
|  0 |      406 | Denver    | False   |
| 10 |     1220 | New York  | False   |
|  2 |     1557 | Boston    | False   |
|  7 |       90 | Seattle   | False   |
|  9 |        3 | Provo     | False   |
| 11 |      323 | Bismark   | False   |
|  4 |        1 | St. Louis | False   |
|  6 |      562 | Detroit   | True    |
|  5 |     8391 | Fresno    | True    |
+----+----------+-----------+---------+

我可以制作条形图就好了:

    fig = go.Figure()
    fig.update_layout(width = 800, height = 400, template = 'plotly_white',xaxis_title = x_title, yaxis_title = y_title)
    fig.add_trace(go.Bar(x = data['City'].tolist(),
                         y = data['COUNT'].tolist()))

    fig.show()

但是,我想根据 Go_NoGo 值更改颜色(“蓝色”如果为真,“红色”如果为假)。

我查看了添加marker=dict(color(list(map(set_color,y)))) 的各种方法,其中set_color 是:

def set_color(value):
     if value:
          return "blue"
     else:
          return "red"

我不知道如何传入第 3 列来设置标记颜色。

我已经尝试了各种选项,可能我的 search-fu 还不够。任何帮助将不胜感激。

【问题讨论】:

    标签: python colors plotly bar-chart


    【解决方案1】:

    您可以使用 marker_color 代替标记。这是一个例子:

    import pandas as pd
    import plotly_graph_objects as go
    
    def Bar_Color(i):
        
        if (i == False):
            return "red"
    
        elif (i == True):
            return "blue"
    
    fig = go.Figure()
    
    fig.update_layout(width = 800, height = 400)
    
    fig.add_trace(go.Bar(x = data['City'].tolist(),
                         y = data['COUNT'].tolist(),
                         marker_color=list(map(Bar_Color, data['Go_NoGo']))
                         )
                  )
    fig.show()
    

    所以预期的输出是底特律和弗雷斯诺是蓝色的,其余的是红色的。

    【讨论】:

      猜你喜欢
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 2019-05-06
      • 2021-03-13
      • 2020-05-22
      • 2021-07-21
      相关资源
      最近更新 更多