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

问题描述 投票:0回答:1
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}

我有上面的代码,在这里我想介绍一下使用'marker'来进行颜色编码,这样bargraph的颜色应该取决于它的值,随着值的增加,颜色也应该改变。

python plotly
1个回答
1
投票

我假设你要找的是这样的东西。

Plot 1: Plotly express and

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()

你可以很容易地将这种方法应用到 plotly. graph_objects中,得到:

Plot 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()
© www.soinside.com 2019 - 2024. All rights reserved.