簡體   English   中英

在matplotlib子圖中旋轉x刻度標簽的問題

[英]Issue with rotating x tick labels in matplotlib subplots

我在讓x軸刻度標簽旋轉時遇到問題。 我已經嘗試使用ax1.set_xticklables(labels, rotation=45)遵循axis.set_xticklabels()的matplotlib文檔。 我已經嘗試過每個帖子都使用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 ['Date']是從計算機上的csv導入的數據框列,但是您可以使用示例頂部的代碼段復制它的較小版本。

因此,經過一番修補后,我自己解決了這個問題。 由於某些原因,Pandas 0.17和matplotlib 1.5嘗試使用df['column'].plot(ax=ax#)繪制線使我無法控制軸的格式。 此外,我對ax1.set_xticklabels(bars['Date'], rotation=45)所做的操作是不正確的,因為它正在將ticklabel設置為整個'Date'列,並且僅基於滴答聲。

我最終要做的是遵循這篇文章的建議,將numpy.datetime64(對matplotlib不友好)中的“日期”轉換為浮點數格式,並使用該值創建新的列“日期”。 然后,創建唯一天數列表並將其轉換為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 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))

有效!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM