'Control a Plotly line color according to its value?
I'm creating a dashboard in which I would like to compare the difference of price between two regions directly. If the price of region 1 is higher, y is POSITIVE, if the price of region 2 is higher, y is NEGATIVE. The problem is that I would like the line and its fill to change color accordingly to its value, so it has a better representation.
I'm using fill='tozeroy'. I would like y-negative = red and y-positive = blue, for the lines and the fill.
def func(est1, est2):
est1, est2 = 'RIO GRANDE DO SUL', 'SANTA CATARINA' # filter to simulate the callback
df1 = df[df.ESTADO.isin([est1])]
df2 = df[df.ESTADO.isin([est2])]
df_final = pd.DataFrame()
df_estado1 = df1.groupby(pd.PeriodIndex(df1['DATA'], freq="M"))['VALOR REVENDA (R$/L)'].mean().reset_index()
df_estado2 = df2.groupby(pd.PeriodIndex(df2['DATA'], freq="M"))['VALOR REVENDA (R$/L)'].mean().reset_index()
df_estado1['DATA'] = pd.PeriodIndex(df_estado1['DATA'], freq="M")
df_estado2['DATA'] = pd.PeriodIndex(df_estado2['DATA'], freq="M")
df_final['DATA'] = df_estado1['DATA'].astype('datetime64[ns]')
df_final['VALOR REVENDA (R$/L)'] = df_estado1['VALOR REVENDA (R$/L)']-df_estado2['VALOR REVENDA (R$/L)']
fig = go.Figure()
fig.add_trace(go.Scatter(name='Comparação', y=df_final['VALOR REVENDA (R$/L)'], x=df_final['DATA'],
fill='tozeroy', mode='lines'))
return fig
Just for help porpouses, that's the "df_final" format which is returned: df_final DataFrame
Here's the graph that is being returned from the function: graph returned
Also, how can I style my fill? Maybe add some gradient etc
Solution 1:[1]
I found this Plotly reference library, where I scraped the information I'm answering you with: https://plotly.com/python/creating-and-updating-figures/#plotly-express
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
title="Using The add_trace() method With A Plotly Express Figure")
fig.add_trace(
go.Scatter(
x=[2, 4],
y=[4, 8],
mode="lines",
line=go.scatter.Line(color="gray"),
showlegend=False)
)
fig.show()
Basically, if you put "df_final" in the place of df, and change the axis's data, you'll be good to go.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dharman |