绘图:如何使用Python对绘图图形对象条形图进行颜色编码?

时间:2020-05-19 13:17:30

标签: python plotly

def update_graph_bar(named_count,**kwargs):

traces = list()
df = pd.DataFrame(list(Message.objects.all().values()))
available_indicators = list(df['content'].unique())
for t in available_indicators:
    traces.append(go.Bar(
        x=[t],
        y=[df[df['content']==t]['timestamp'].count()],
        name='{}'.format(t),text=[df[df['content']==t]['timestamp'].count()],
        textposition='auto'
        ))
layout = plotly.graph_objs.Layout(barmode='group',paper_bgcolor='#00FFFF',
    plot_bgcolor='rgba(0,0,0,0)',)
return {'data': traces,
      'layout': layout}

我有上面的代码,在这里我要介绍使用“标记”的颜色编码,以使条形图的颜色取决于其值。随着值的增加,颜色也会改变。

1 个答案:

答案 0 :(得分:1)

我假设您正在寻找这样的东西:

情节1:情节表达和

enter image description here

可以很容易地这样生成:

import plotly.express as px
data = px.data.gapminder()

data_canada = data[data.country == 'Canada']
fig = px.bar(data_canada, x='year', y='pop',
             hover_data=['lifeExp', 'gdpPercap'], color='lifeExp',
             labels={'pop':'population of Canada'}, height=400)
fig.show()

您可以轻松地将该方法适应于plot.graph_objects以获得:

图2: go.Bar()'viridis'

enter image description here

代码2:

import plotly.graph_objects as go

fig = go.Figure()

x=[1,2,3]
y=[4,5,6]
z=[12,24,48]

fig.add_trace(go.Bar(x=x, y=y,
                     marker=dict(color = z,
                     colorscale='viridis')))

fig.show()

您甚至可以应用自己的自定义色阶:

图3:自定义颜色

enter image description here

代码3:

import plotly.graph_objects as go

fig = go.Figure()

x=[1,2,3]
y=[4,5,6]
z=[12,24,48]

customscale=[[0, "rgb(255, 0, 0)"],
            [0.1, "rgb(255, 0, 0)"],
            [0.9, "rgb(0, 0, 255)"],
            [1.0, "rgb(0, 0, 255)"]]

fig.add_trace(go.Bar(x=x, y=y,
                     marker=dict(color = z,
                     colorscale=customscale)))

fig.show()

code 3将颜色映射到变量的相对大小时,code 4将向您展示如何将颜色映射到具有指定阈值的绝对值:

图4:由变量的绝对值分配的颜色

enter image description here

代码4:

import plotly.graph_objects as go

fig = go.Figure()

x=[1,2,3]
y=[25,75, 110]
z=[12,24,48]

def SetColor(y):
        if(y >= 100):
            return "red"
        elif(y >= 50):
            return "yellow"
        elif(y >= 0):
            return "green"

fig.add_trace(go.Bar(x=x, y=y,
                     marker=dict(color = list(map(SetColor, y)))))

fig.show()