Hi everyone,
I’m working on the Time Series Visualizer project as part of the Data Analysis course, and I’m facing an issue with the bar chart visualization. The code runs fine, but I keep encountering the following error:
“AssertionError: 57 != 49: Expected a different number of bars in bar chart.”
From what I’ve gathered in previous discussions, this error might be related to the number of elements in the legend being counted as additional bars in the chart. However, after going through these discussions, I still haven’t been able to pinpoint the root cause of the problem.
I’ve included my code below. Any suggestions or insights would be greatly appreciated.
Thank you in advance for your help!
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
# Importing data
data = 'fcc-forum-pageviews.csv'
df = pd.read_csv(data,
parse_dates = ['date'],
index_col = 0)
# Cleaning data
upper_bound = df.value.quantile(0.975)
lower_bound = df.value.quantile(0.025)
df = df[
(df['value'] < upper_bound) &
(df['value'] > lower_bound)
]
def draw_bar_plot():
df_bar = df.reset_index()
df_bar['year'] = pd.DatetimeIndex(df_bar.date).year
df_bar['Months'] = pd.DatetimeIndex(df_bar.date).month
df_bar['day'] = pd.DatetimeIndex(df_bar.date).day
month_names = [
"January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"
]
df_bar['Months'] = df_bar['Months'].apply(lambda x: month_names[x - 1])
df_bar= df_bar.groupby(['year','Months'])['value'].mean()
df_bar = pd.DataFrame(df_bar).reset_index()
month_order = [
"January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"
]
palette = sns.color_palette("tab10", n_colors=12)
facet = sns.catplot(data = df_bar,
x = 'year',
y = 'value',
hue = 'Months',
kind = 'bar',
palette = palette,
legend_out = False,
hue_order = month_order
)
facet.set_axis_labels('Years', 'Average Page Views')
facet.set_xticklabels(rotation=90)
# Save image and return fig (don't change this part)
fig = plt.gcf()
fig.savefig('bar_plot.png')
return fig