问题
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}
I have the above code and here I want to introduce colorcoding using 'marker' in such a way that the color of bargraph should be dependent on its value. as the value increases the color should also change.
回答1:
I'm assuming you're looking for something like this:
Plot 1: Plotly express and
Which can easily be produced like this:
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()
You can easily adapt that approach to plotly.graph_objects to get:
Plot 2: go.Bar()
and 'viridis'
Code 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()
And you can even apply your own custom color scale:
Plot 3: Custom colors
Code 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()
While code 3
maps colors to relative sizes of a variable, code 4
will show you how you can map colors to absolute values with specified thresholds:
Plot 4: Colors assigned by absolute values of a variable
Code 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()
来源:https://stackoverflow.com/questions/61892036/plotly-how-to-colorcode-plotly-graph-objects-bar-chart-using-python