Matplotlib Question : Why is there an extra plot being displayed in my code output?

If I remove the plt.figure line of code, it displays 2 plots but not as intended(side by side) rather above and below. Also tried using fix, ax1 =…but that also did not help.
Checked the project walkthrough video also, unable to find anything wrong in the code.
Can anyone please help me out to understand what is being overlooked by me?

Thanks a bunch in advance.

import codecademylib
from matplotlib import pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

visits_per_month = [9695, 7909, 10831, 12942, 12495, 16794, 14161, 12762, 12777, 12439, 10309, 8724]

# numbers of limes of different species sold each month
key_limes_per_month = [92.0, 109.0, 124.0, 70.0, 101.0, 79.0, 106.0, 101.0, 103.0, 90.0, 102.0, 106.0]
persian_limes_per_month = [67.0, 51.0, 57.0, 54.0, 83.0, 90.0, 52.0, 63.0, 51.0, 44.0, 64.0, 78.0]
blood_limes_per_month = [75.0, 75.0, 76.0, 71.0, 74.0, 77.0, 69.0, 80.0, 63.0, 69.0, 73.0, 82.0]


# create your figure here
x_values=list(range(1,len(months)+1))


plt.figure(figsize=(24,12))
ax1=plt.subplot(1,2,1)
ax1.set_xticks(x_values)
ax1.set_xticklabels(months, rotation = 90)
ax1.set_xlabel("Months")
ax1.set_ylabel("Visits per month")
ax1.set_title("Total page visits over the past year")
ax1.plot(x_values,visits_per_month,marker='o')
plt.show()

ax2=plt.subplot(1,2,2)
ax2.plot(x_values,key_limes_per_month,color="green",marker="s",label="key limes")
ax2.plot(x_values,persian_limes_per_month,color="black",marker="o",label="persian limes")
ax2.plot(x_values,blood_limes_per_month,color="red",marker="^",label="blood limes")
ax2.set_xticks(x_values)
ax2.set_xticklabels(months,rotation=90)
ax2.set_xlabel("Months")
ax2.set_title("Visits for different types of lime")
ax2.set_ylabel("Visits per month")
ax2.legend()
plt.subplots_adjust(wspace=0.4)
plt.show()

plt.savefig("Annual report of page visits")

Also link for the same code -https://gist.github.com/3cbb71278fdacb5cc33f2e4ba44d1595

Not sure if this will work but here is a link to the project :https://www.codecademy.com/paths/visualize-data-with-python/tracks/graphing-in-python-dvp/modules/matplotlib-dvp/projects/matplotlib-proj-i

You don’t want to remove the plt.figure line because that is the figure that should contain both subplots. What you want to remove is the first plt.show(), since that is called before the second subplot has been created. If you remove the first plt.show() and just leave the one at the end, it should output 1 figure with 2 subplots side by side.

3 Likes

Thanks a lot, that worked :slight_smile: .

2 Likes