Yomi.blaze93
Yomi.blaze93

Reputation: 425

How to plot positive and Negative Bar chart

I have a dataset named pct below

I want to have positive and negative bar charts using ggplot2 or plotly package.

given the dataset in the table below

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%

I want to get something like this

enter image description here

Upvotes: 0

Views: 1527

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31156

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

enter image description here

Upvotes: 0

Related Questions