Search code examples
pythonpandasplot

How to nicely format the X-axis labels on a pandas bar chart


Run the following code:

covid = pd.read_csv("https://covid.ourworldindata.org/data/owid-covid-data.csv")
covid.set_index("date", inplace=True)
covid.index = pd.to_datetime(covid.index)
covid[covid.location=="Denmark"].new_cases_smoothed_per_million.plot()

And you get nicely formatted X-axis labels:

enter image description here

Use the bar method, and you don't get nicely formatted X-axis labels:

covid[covid.location=="Denmark"].new_cases_smoothed_per_million.plot.bar()

enter image description here

How do I get nicely formatted X-axis labels on the bar chart?


Solution

  • You can try something like this:

    covid = pd.read_csv("https://covid.ourworldindata.org/data/owid-covid-data.csv")
    covid.set_index("date", inplace=True)
    covid.index = pd.to_datetime(covid.index)
    df = covid.loc[covid.location=="Denmark", 'new_cases_smoothed_per_million']
    g =  df.groupby(pd.Grouper(freq='M')).sum()
    ax = g.plot.bar(figsize=(15,6), rot=0)
    def line_format(label):
        """
        Convert time label to the format of pandas line plot
        """
        month = label.month_name()[:3]
        if month == 'Jan':
            month += f'\n{label.year}'
        return month
    
    ax.set_xticklabels(map(line_format, g.index), fontsize=8);
    

    Output:

    enter image description here