Issue
I am trying to create a plot made of 5 subplots made of simple line graphs using Matplotlib and Pandas on Visual Studio code. However, for some reason the image always looks very small and clumped up even if I make the figure very big. I tried modifying the space between figures with subplots_adjust but that doesn't change anything.
Here is my code
ax1 = plt.subplot(1, 5, 1)
ax1 = plt.plot(returns["MSFT"])
plt.xlabel("Date")
plt.ylabel("Daily MSFT Returns")
plt.title("MSFT Returns Over Time")
ax2 = plt.subplot(1, 5, 2)
ax2 = plt.plot(returns["AMZN"])
plt.xlabel("Date")
plt.ylabel("Daily AMZN Returns")
plt.title("AMZN Returns Over Time")
ax3 = plt.subplot(1, 5, 3)
ax3 = plt.plot(returns["AAPL"])
plt.xlabel("Date")
plt.ylabel("Daily AAPL Returns")
plt.title("AAPL Returns Over Time")
ax4 = plt.subplot(1, 5, 4)
ax4 = plt.plot(returns["GOOG"])
plt.xlabel("Date")
plt.ylabel("Daily GOOG Returns")
plt.title("GOOG Returns Over Time")
ax5 = plt.subplot(1, 5, 5)
ax5 = plt.plot(returns["FB"])
plt.xlabel("Date")
plt.ylabel("Daily FB Returns")
plt.title("FB Returns Over Time")
plt.figure(figsize=(100, 100))
plt.subplots_adjust(wspace = 10)
plt.show()
Solution
Update: As BigBen mentioned, you can further simplify with a loop. For example, here we put all subplot axes in axes
and company names in names
, then zip and iterate:
fix, axes = plt.subplots(nrows=1, ncols=5, figsize=(20, 5))
names = ['MSFT', 'AMZN', 'AAPL', 'GOOG', 'FB']
for ax, name in zip(axes, names):
ax.plot(returns[name])
ax.set_ylabel(f'Daily {name} Returns')
ax.set_title(f'{name} Returns Over Time')
Generally it's easier to first create the subplot axes ax1
, ..., ax5
using plt.subplots()
with figsize
. Then operate on those premade axes handles like ax1.plot()
instead of plt.plot()
, ax1.set_xlabel()
instead of plt.xlabel()
, etc.
# first create ax1~ax5
fig, (ax1,ax2,ax3,ax4,ax5) = plt.subplots(nrows=1, ncols=5, figsize=(20, 5))
ax1.plot(returns["MSFT"]) # not plt.plot(...)
ax1.set_xlabel("Date") # not plt.xlabel(...)
ax1.set_ylabel("Daily MSFT Returns") # not plt.ylabel(...)
ax1.set_title("MSFT Returns Over Time") # not plt.title(...)
ax2.plot(returns["AMZN"])
ax2.set_xlabel("Date")
ax2.set_ylabel("Daily AMZN Returns")
ax2.set_title("AMZN Returns Over Time")
ax3.plot(returns["AAPL"])
ax3.set_xlabel("Date")
ax3.set_ylabel("Daily AAPL Returns")
ax3.set_title("AAPL Returns Over Time")
ax4.plot(returns["GOOG"])
ax4.set_xlabel("Date")
ax4.set_ylabel("Daily GOOG Returns")
ax4.set_title("GOOG Returns Over Time")
ax5.plot(returns["FB"])
ax5.set_xlabel("Date")
ax5.set_ylabel("Daily FB Returns")
ax5.set_title("FB Returns Over Time")
Answered By - tdy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.