[英]Plotly bar chart - change color based on positive/negative value - python
I have the following code which plots a bar chart (1 series), but I need the bars to be coloured blue if the 'Net' value is positive, and red if its negative:我有以下绘制条形图(1 个系列)的代码,但如果“净”值为正,我需要将条形图着色为蓝色,如果为负值,则条形图为红色:
import pandas as pd
import plotly.graph_objects as go
df = pd.DataFrame({
'Net':[15,20,-10,-15],
'Date':['07/14/2020','07/15/2020','07/16/2020','07/17/2020']
})
df['Date'] = pd.to_datetime(df['Date'])
fig = go.Figure(data=[go.Bar(name='Net', x=df['Date'], y=df['Net'])])
fig.update_layout(barmode='stack')
fig.show()
You can check documentation here .您可以在此处查看文档。 Full code as following完整代码如下
import pandas as pd
import plotly.graph_objects as go
import numpy as np
# Data
df = pd.DataFrame({
'Net':[15,20,-10,-15],
'Date':['07/14/2020','07/15/2020','07/16/2020','07/17/2020']
})
df['Date'] = pd.to_datetime(df['Date'])
## here I'm adding a column with colors
df["Color"] = np.where(df["Net"]<0, 'red', 'green')
# Plot
fig = go.Figure()
fig.add_trace(
go.Bar(name='Net',
x=df['Date'],
y=df['Net'],
marker_color=df['Color']))
fig.update_layout(barmode='stack')
fig.show()
@rpanai that is a great answer and got me where I needed to go. I wanted to simply add a way to do the same if using plotly.express
. @rpanai 这是一个很好的答案,让我到达了我需要的地方 go。如果使用plotly.express
,我想简单地添加一种方法来做同样的事情。
Note that most of this is the same as above.请注意,其中大部分与上面相同。
import pandas as pd
import numpy as np
import plotly.express as px
df = pd.DataFrame({
'Net':[15,20,-10,-15],
'Date':['07/14/2020','07/15/2020','07/16/2020','07/17/2020']
})
df['Date'] = pd.to_datetime(df['Date'])
df["Color"] = np.where(df["Net"]<0, 'red', 'green')
# PLOT
fig = px.bar(df,x="Date",y="Net")
# COLOR
fig.update_traces(marker_color=df["Color"])
fig.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.