Changing bar plot order

The month bars are out of order and I can’t find a method to change them. The boxplot has a order argument so it works for that but I can’t get my code working for the bar plot. I could change the legend and the test passes but the bars are still out of order.

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

# Import data (Make sure to parse dates. Consider setting index column to 'date'.)
df = pd.read_csv('fcc-forum-pageviews.csv')  

# Clean data
df = df[(df['value'] >= df['value'].quantile(0.025)) & (df['value'] <= df['value'].quantile(0.975))]
df['date'] = pd.to_datetime(df['date'])


def draw_line_plot():
    # Draw line plot
    fig = plt.figure(figsize=(12, 6))
    plt.plot(df.date, df.value)
    plt.title('Daily freeCodeCamp Forum Page Views 5/2016-12/2019')
    plt.xlabel('Date')
    plt.ylabel('Page Views')

    # Save image and return fig (don't change this part)
    fig.savefig('line_plot.png')
    return fig

def draw_bar_plot():
    # Copy and modify data for monthly bar plot
    df_bar = df.copy()
    df_bar['year'] = [d.year for d in df_bar.date]
    df_bar['month'] = [d.strftime('%B') for d in df_bar.date]
    df_bar = df_bar.groupby(['year', 'month'])['value'].agg('mean').reset_index()
    table = pd.pivot_table(df_bar, values='value', index='year', columns='month', dropna=False)
    
    # Draw bar plot
    ax = table.plot(kind='bar')
    fig = ax.get_figure()
    fig.set_size_inches(12, 6)
    ax.set_xlabel('Years')
    ax.set_ylabel('Average Page Views')

    # Save image and return fig (don't change this part)
    fig.savefig('bar_plot.png')
    return fig

def draw_box_plot():
    # Prepare data for box plots (this part is done!)
    df_box = df.copy()
    df_box.reset_index(inplace=True)
    df_box['year'] = [d.year for d in df_box.date]
    df_box['month'] = [d.strftime('%b') for d in df_box.date]

    # Draw box plots (using Seaborn)
    fig, (ax1, ax2) = plt.subplots(1, 2)
    fig.set_size_inches(12, 6)
    sns.boxplot(x="year", y="value", data=df_box, ax=ax1)
    sns.boxplot(x="month", y="value", data=df_box, ax=ax2, order=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct','Nov', 'Dec'])
    
    ax1.set_title('Year-wise Box Plot (Trend)')
    ax2.set_title('Month-wise Box Plot (Seasonality)')
    ax1.set_xlabel('Year')
    ax1.set_ylabel('Page Views')
    ax2.set_xlabel('Month')
    ax2.set_ylabel('Page Views')

    # Save image and return fig (don't change this part)
    fig.savefig('box_plot.png')
    return fig

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.54

Challenge: Page View Time Series Visualizer

Link to the challenge:

Your solution for the bar plot is the same as this. You have to set the order. Seaborn will plot bar plots, too. You may have to do some more data processing to use seaborn to make the bar plot, but you will also probably have to do more to get the month order correct and use pandas anyway. You could also check the pandas documentation to see if you can set the order to plot() (I looked; I don’t think you can, so you would have to reorder the data to get the months in order). I used seaborn, FWIW.

Also, the months are in order (alphabetical) just not the order (chronological) that you want. Computers are so annoyingly literal.

1 Like

Thanks for the help. I end up changing the month index from word form to number so that it’ll sort itself and renaming the legend afterwards.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.