Tell us what’s happening:
Describe your issue in detail here.
Hi!
I have a two-part question
-
how to change the legend colouring? what I mean is I want my legend to look like how figure2.png is and not like this:
-
is there a better way to plot the barplot using
sns.barplot()and pass the test than what I did in the code below?
(PS: I wrote the code that way because I was failing the test where it checks for the number of bars in the plot and I was getting 57 instead of 49. but the code I wrote does get the job done but the plot is a bit ugly)
Your code so far
def draw_bar_plot():
# Copy and modify data for monthly bar plot
df_bar = df.copy()
# * filling in the missing values to complete one full year
fill_range = pd.date_range("2016-01-01", "2019-12-31")
df_bar = df_bar.reindex(fill_range, fill_value=np.nan)
df_bar["year"] = df_bar.index.year
df_bar["month"] = df_bar.index.month_name()
df_bar = df_bar.groupby(["year", "month"]).mean()
# * Fill the NaN values with 0 so that they appear on the plot
# ! Note: Do not do this before finding the mean
# ! as it will add to the total number when finding the mean and mess your calculations
df_bar = df_bar.reset_index().fillna(0.0)
# Draw bar plot
fig, ax = plt.subplots(figsize=(12, 9))
order = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
# * The only reason for the legend to be false is to pass one testcase
plot_bar = sns.barplot(
data=df_bar,
x="year",
y="value",
hue="month",
ax=ax,
hue_order=order,
width=0.5,
legend=False,
palette=sns.color_palette("bright", 12),
)
plot_bar.legend(labels=order, title="Months")
plot_bar.set_xlabel("Years")
plot_bar.set_ylabel("Average Page Views")
# Save image and return fig (don't change this part)
fig.savefig("bar_plot.png")
return fig
The replit link is here.
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/118.0
Challenge: Data Analysis with Python Projects - Page View Time Series Visualizer
Link to the challenge:
