- a trace for positive values and a trace for negative values
- use textformat for labels above / below bars
Built before I saw this was R. Approach to building plotly figure is the same.
import pandas as pd
import io
import plotly.express as px
df = pd.read_csv(
io.StringIO(
"""Month,pct
Jan-20,45%
Feb-20,34%
Mar-20,-15%
Apr-20,-11%
May-20,17%
Jun-20,15%
Jul-20,45%
Aug-20,17%
Sep-20,-11%
Oct-20,-21%
Nov-20,74%
Dec-20,12%"""
)
)
df["pct"] = pd.to_numeric(df["pct"].str[:-1]) / 100
df["Month"] = pd.to_datetime("01-" + df["Month"])
px.bar(
df,
x="Month",
y="pct",
color=df["pct"] > 0,
color_discrete_map={True: "green", False: "red"},
text_auto=True
).update_layout(yaxis={"tickformat": "3.0%"}, xaxis_dtick="M1", showlegend=False)
