在matplotlib子图中旋转x刻度标签的问题

时间:2016-01-07 16:57:41

标签: python matplotlib

我的问题是让我的x轴刻度标签旋转。我尝试使用ax1.set_xticklables(labels, rotation=45)跟踪axes.set_xticklabels()的matplotlib文档。我尝试过每this post使用plt.setp,但仍无法成功旋转标签。作为参考,我的代码如下:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime 

print("Enter a symbol:")
symbol = input()
symbol = symbol.upper()
print("Enter an interval:")
interval = input()
print("You entered: " + symbol)

# Obtain minute bars of symbol from Google Finance for the last ten days

bars = pd.read_csv(r'http://www.google.com/finance/getprices?i={}&p=10d&f=d,o,h,l,c,v&df=cpct&q={}'.format(interval, symbol), sep=',', engine='python', skiprows=7, header=None, names=['Date', 'Close', 'High', 'Low', 'Open', 'Volume'])

bars['Date'] = bars['Date'].map(lambda x: int(x[1:]) if x[0] == 'a' else int(x))
bars['Date'] = bars['Date'].map(lambda u: u * 60 if u < 400 else u)
threshold = 24000
bars['Timestamp'] = bars[bars['Date']>threshold].loc[:, 'Date']
bars['Timestamp'] = bars['Timestamp'].fillna(method='ffill')
bars['Date'] = bars.apply(lambda x: x.Date + x.Timestamp if x.Date < threshold else x.Date, axis=1)
bars.drop('Timestamp', axis=1, inplace=True)
bars['Date'] = bars['Date'].map(lambda v: datetime.datetime.fromtimestamp(v) if v < 25000 else datetime.datetime.fromtimestamp(v))

# Plot equity curve
fig = plt.figure()
fig.patch.set_facecolor('white') # Set the outer color to white
ax1 = fig.add_subplot(211, ylabel='Price in $')
ax1.set_xticklabels(bars['Date'], rotation=45)

# Plot the DIA closing price overlaid with the moving averages
bars['Close'].plot(ax=ax1, color='r', lw=2.)
signals[['short_mavg', 'long_mavg']].plot(ax=ax1,lw=2.)

# Plot the "buy" trades agains DIA
ax1.plot(signals.ix[signals.positions == 1.0].index, signals.short_mavg[signals.positions == 1.0], '^', markersize=10, color='m')
ax1.plot(signals.ix[signals.positions == 2.0].index, signals.short_mavg[signals.positions == 2.0], '^', markersize=10, color='m')

# Plot the "sell" trades against AAPL
ax1.plot(signals.ix[signals.positions == -1.0].index, signals.short_mavg[signals.positions == -1.0], 'v', markersize=10, color='b')
ax1.plot(signals.ix[signals.positions == -2.0].index, signals.short_mavg[signals.positions == -2.0], 'v', markersize=10, color='b')

# Plot the equity curve in dollars
ax2 = fig.add_subplot(212, xticklabels=bars['Date'], ylabel='Portfolio value in $')
ax2.set_xticklabels(bars['Date'], rotation=45)
returns['total'].plot(ax=ax2, lw=2.)

# Plot the "buy" and "sell" trades against the equity curve
ax2.plot(returns.ix[signals.positions == 1.0].index, returns.total[signals.positions == 1.0], '^', markersize=10, color='m')
ax2.plot(returns.ix[signals.positions == -1.0].index, returns.total[signals.positions == -1.0], 'v', markersize=10, color='b')
ax2.plot(returns.ix[signals.positions == 2.0].index, returns.total[signals.positions == 2.0], '^', markersize=10, color='m')
ax2.plot(returns.ix[signals.positions == -2.0].index, returns.total[signals.positions == -2.0], 'v', markersize=10, color='b')

# Plot the figure
fig.savefig("C:/users/gph/desktop/tradingalgorithm/30_60EMA_cross_backtest.png")

bars [&#39; Date&#39;]是从我的机器上的csv导入的数据帧列,但您可以使用示例顶部的代码段复制它的较小版本。

1 个答案:

答案 0 :(得分:0)

因此经过一些修修补补后,我自己想出了这个。出于某种原因,Pandas 0.17和matplotlib 1.5试图用df['column'].plot(ax=ax#)绘制线条,这使我无法控制轴的格式。此外,我使用ax1.set_xticklabels(bars['Date'], rotation=45)做的事情是错误的,因为它将ticklabels设置为&#39; Date&#39;的全部内容。列,仅根据刻度数显示前几个。

我最终做的是遵循this post的建议,转换日期&#39;从numpy.datetime64(对matplotlib不友好)到浮动日格式,并创建一个新列&#39;日期&#39;有这个值。然后创建一个唯一日期列表并将其转换为ISO日期格式。

dates = [md.date2num(t) for t in bars.Date]
bars['Dates'] = dates
days = np.unique(np.floor(bars['Dates']), return_index=True)
iso_days= []
for n in np.arange(len(days[0])):
    iso_days.append(datetime.date.isoformat(md.num2date(days[0][n]))) 

其余的很简单,我对我调用subplots()的方式进行了一些更改,并为看起来设置了sharex = True。

# Plot two subplots to assess trades and equity curve. 
fig, (ax1, ax2) = plt.subplots(, 1, sharex=True)
fig.patch.set_facecolor('white') # Set the outer color to white
ax1.set_ylabel('Price in $')
# Plot the DIA closing price overlaid with the moving averages
ax1.set_xticks(days[1])

ax1.plot(bars.index, bars['Close'], color='r', lw=2.)
ax1.plot(bars.index, signals['short_mavg'], 'b', bars.index, signals['long_mavg'], 'g',lw=2.)

# Plot the "buy" trades agains DIA
ax1.plot(signals.ix[signals.positions == 1.0].index, signals.short_mavg[signals.positions == 1.0], '^', markersize=10, color='m')
ax1.plot(signals.ix[signals.positions == 2.0].index, signals.short_mavg[signals.positions == 2.0], '^', markersize=10, color='m')

# Plot the "sell" trades against AAPL
ax1.plot(signals.ix[signals.positions == -1.0].index, signals.short_mavg[signals.positions == -1.0], 'v', markersize=10, color='b')
ax1.plot(signals.ix[signals.positions == -2.0].index, signals.short_mavg[signals.positions == -2.0], 'v', markersize=10, color='b')

# Plot the equity curve in dollars
ax2.set_ylabel('Portfolio value in $')
ax2.plot(bars.index, returns.total, lw=2.)
ax2.set_xticklabels(iso_days, rotation=45, horizontalalignment='right')

# Plot the "buy" and "sell" trades against the equity curve
ax2.plot(returns.ix[signals.positions == 1.0].index, returns.total[signals.positions == 1.0], '^', markersize=10, color='m')
ax2.plot(returns.ix[signals.positions == -1.0].index, returns.total[signals.positions == -1.0], 'v', markersize=10, color='b')
ax2.plot(returns.ix[signals.positions == 2.0].index, returns.total[signals.positions == 2.0], '^', markersize=10, color='m')
ax2.plot(returns.ix[signals.positions == -2.0].index, returns.total[signals.positions == -2.0], 'v', markersize=10, color='b')

# Plot the figure
plt.tight_layout()
plt.show()
fig.savefig("C:/users/gph/desktop/tradingalgorithm/{}_{}EMA_cross_backtest.png".format(short_window, long_window))

It Worked!