13

Ubuntu 10.0.4 で matplotlib 1.2.x と Python 2.6.5 を使用しています。上部のプロットと下部のプロットで構成される単一のプロットを作成しようとしています。

X 軸は時系列の日付です。上部のプロットにはデータのローソク足プロットが含まれ、下部のプロットはバー タイプのプロットで構成され、独自の Y 軸 (左側にも - 上部のプロットと同じ) が含まれます。これら 2 つのプロットは重複してはなりません。

ここに私がこれまでに行ったことのスニペットがあります。

datafile = r'/var/tmp/trz12.csv'
r = mlab.csv2rec(datafile, delimiter=',', names=('dt', 'op', 'hi', 'lo', 'cl', 'vol', 'oi'))

mask = (r["dt"] >= datetime.date(startdate)) & (r["dt"] <= datetime.date(enddate))
selected = r[mask]
plotdata = zip(date2num(selected['dt']), selected['op'], selected['cl'], selected['hi'], selected['lo'], selected['vol'], selected['oi'])

# Setup charting 
mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
alldays    = DayLocator()               # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # Eg, Jan 12
dayFormatter = DateFormatter('%d')      # Eg, 12
monthFormatter = DateFormatter('%b %y')

# every Nth month
months = MonthLocator(range(1,13), bymonthday=1, interval=1)

fig = pylab.figure()
fig.subplots_adjust(bottom=0.1)
ax = fig.add_subplot(111)
ax.xaxis.set_major_locator(months)#mondays
ax.xaxis.set_major_formatter(monthFormatter) #weekFormatter
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = price
ax.grid(True)

candlestick(ax, plotdata, width=0.5, colorup='g', colordown='r', alpha=0.85)

ax.xaxis_date()
ax.autoscale_view()
pylab.setp( pylab.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

# Add volume data 
# Note: the code below OVERWRITES the bottom part of the first plot
# it should be plotted UNDERNEATH the first plot - but somehow, that's not happening
fig.subplots_adjust(hspace=0.15)
ay = fig.add_subplot(212)
volumes = [ x[-2] for x in plotdata]
ay.bar(range(len(plotdata)), volumes, 0.05)

pylab.show()

上記のコードを使用して 2 つのプロットを表示できましたが、下のプロットには 2 つの問題があります。

  1. それは最初の(上)プロットの下部を完全に上書きします-まるで2番目のプロットが最初のプロットと同じ「キャンバス」に描かれているかのように-どこで/なぜそれが起こっているのかわかりません。

  2. 既存の X 軸を独自のインデックスで上書きします。X 軸の値 (日付) は 2 つのプロット間で共有する必要があります。

コードで何が間違っていますか?. 誰かが 2 番目 (下) のプロットが最初 (上) のプロットを上書きする原因を特定できますか?どうすればこれを修正できますか?

上記のコードで作成されたプロットのスクリーンショットを次に示します。

間違ったプロット

[[編集]]

hwlau の提案に従ってコードを変更した後、これが新しいプロットです。2 つのプロットが分離されているという点で最初のものよりは優れていますが、次の問題が残ります。

  1. X 軸は 2 つのプロットで共有する必要があります (つまり、X 軸は 2 番目の [下] プロットに対してのみ表示する必要があります)。

  2. 2 番目のプロットの Y 値の形式が正しくないようです

部分的に正しいプロット

これらの問題は非常に簡単に解決できるはずですが、最近matplotlibでプログラミングを始めたばかりなので、私のmatplotlib fuは現時点ではあまり良くありません。どんな助けでも大歓迎です。

4

3 に答える 3

12

あなたのコードにはいくつかの問題があるようです:

  1. figure.add_subplotsの完全な署名で使用してsubplot(nrows, ncols, plotNum)いた場合、最初のプロットが 1 行 1 列を要求し、2 番目のプロットが 2 行 1 列を要求していることがより明白になる可能性があります。したがって、最初のプロットは図全体を埋めています。 useが続くfig.add_subplot(111)の ではなく、が続きます。fig.add_subplot(212)fig.add_subplot(211)fig.add_subplot(212)

  2. 軸の共有は、add_subplot次を使用してコマンドで行う必要がありますsharex=first_axis_instance

実行できるはずの例をまとめました。

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates


import datetime as dt


n_pts = 10
dates = [dt.datetime.now() + dt.timedelta(days=i) for i in range(n_pts)]

ax1 = plt.subplot(2, 1, 1)
ax1.plot(dates, range(10))

ax2 = plt.subplot(2, 1, 2, sharex=ax1)
ax2.bar(dates, range(10, 20))

# Now format the x axis. This *MUST* be done after all sharex commands are run.

# put no more than 10 ticks on the date axis.  
ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
# format the date in our own way.
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

# rotate the labels on both date axes
for label in ax1.xaxis.get_ticklabels():
    label.set_rotation(30)
for label in ax2.xaxis.get_ticklabels():
    label.set_rotation(30)

# tweak the subplot spacing to fit the rotated labels correctly
plt.subplots_adjust(hspace=0.35, bottom=0.125)

plt.show()

それが役立つことを願っています。

于 2012-04-04T12:27:12.697 に答える
6

You should change this line:

ax = fig.add_subplot(111)

to

ax = fig.add_subplot(211)

The original command means that there is one row and one column so it occupies the whole graph. So your second graph fig.add_subplot(212) cover the lower part of the first graph.

Edit

If you dont want the gap between two plots, use subplots_adjust() to change the size of the subplots margin.

于 2012-04-04T10:18:56.843 に答える