I'm trying to do some basic plotting of stocks using matplot lib and I'm stumped on trying to fill the volume part of the plot.
I'm trying to plot in two seperate charts (one on top of the other) a stocks price and volume. When I plot 2 straight forward lines (ATTEMPT 1 in the code) it looks fine - as you would expect.
When I try and fill beneath the volume line (ATTEMPT 2 in the code), the price plot looks completely squished into about 5 pixels wide and there's nothing in the second, volume plot.
I assume it's something to do with the x-axis (date) series as its only explicitly set in ATTEMPT 2.
Also, I have attempted to plot the same data in a single graph with twin axis. I get the same result only within a single chart. I'm assuming the same solution will fix the issue with both types of chart?
Also, can someone give me a hint on how to shrink the scale of the y-axis?
What am I missing?
Thanks!
Ben
import datetime
import numpy as np
import matplotlib.colors as colors
import matplotlib.finance as finance
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
# get the stock data
fh = finance.fetch_historical_yahoo('AAPL', (2007, 2, 12), (2011, 2, 12))
r = mlab.csv2rec(fh)
fh.close()
r.sort()
# *** ATTEMPT 1: 2 standard line plots ******************************
f, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=False)
ax1.plot(r.close)
ax2.plot(r.volume)
f.subplots_adjust(hspace=0)
# *** ATTEMPT 2: Fill the volume plot *******************************
f, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=False)
ax1.plot(r.close)
ax2.fill_between(r.date,0, r.volume, facecolor='#0079a3', alpha=0.4)
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
Since you link the two xaxes, they should share the same x axis data. Using the plot(x,y)
syntax instead of plot(y)
should solve the problem.
f, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=False)
ax1.plot(r.date,r.close)
ax2.fill_between(r.date,0, r.volume, facecolor='#0079a3', alpha=0.4)
f.subplots_adjust(hspace=0)