Python matplotlib子批次中旋转x记号标签的问题

Python matplotlib子批次中旋转x记号标签的问题,python,matplotlib,Python,Matplotlib,我在旋转x轴刻度标签时遇到问题。我已经尝试过使用ax1来遵循Axis.setxticklables()的matplotlib文档。setxticklables(标签,旋转=45)。我尝试过使用plt.setp per,但仍然无法成功旋转标签。作为参考,我的代码如下: import matplotlib.pyplot as plt import numpy as np import pandas as pd import datetime print("Enter a symbol:") sy

我在旋转x轴刻度标签时遇到问题。我已经尝试过使用ax1来遵循Axis.setxticklables()的matplotlib文档。setxticklables(标签,旋转=45)。我尝试过使用plt.setp per,但仍然无法成功旋转标签。作为参考,我的代码如下:

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")
导入matplotlib.pyplot作为plt
将numpy作为np导入
作为pd进口熊猫
导入日期时间
打印(“输入符号:”)
符号=输入()
symbol=symbol.upper()
打印(“输入间隔:”)
间隔=输入()
打印(“您输入:”+符号)
#在过去的十天里,从谷歌金融获取每分钟的符号条
条形图=局部放电读数(r'http://www.google.com/finance/getprices?i={}&p=10d&f=d,o,h,l,c,v&df=cpct&q={}。格式(间隔,符号),sep=',',engine='python',skiprows=7,header=None,name=['Date','Close','High','Low','Open','Volume'])
条['Date']=条['Date'].映射(λx:int(x[1:]),如果x[0]='a'else int(x))
条形图['Date']=条形图['Date'].map(λu:u*60,如果u<400,则u*60)
阈值=24000
条形图['Timestamp']=条形图[bar['Date']>阈值].loc[:,'Date']
条['Timestamp']=条['Timestamp'].fillna(method='ffill')
条形图['Date']=条形图。应用(λx:x.Date+x.时间戳,如果x.Date<阈值else x.Date,轴=1)
条数下降('Timestamp',轴=1,在位=True)
bars['Date']=bars['Date'].map(λv:datetime.datetime.fromtimestamp(v),如果v<25000,则为datetime.datetime.fromtimestamp(v))
#绘制权益曲线
图=plt.图()
图.patch.set_facecolor(“白色”)#将外部颜色设置为白色
ax1=图add_子批次(211,ylabel='Price in$')
ax1.设置X刻度线(条['Date'],旋转=45)
#绘制覆盖移动平均线的DIA收盘价
条形图['Close'].绘图(ax=ax1,color=r',lw=2)
信号['short_mavg'、'long_mavg']]。绘图(ax=ax1,lw=2。)
#重新规划“买入”交易
ax1.plot(signals.ix[signals.positions==1.0]。索引,signals.short_mavg[signals.positions==1.0],“^”,markersize=10,color='m')
ax1.plot(signals.ix[signals.positions==2.0]。索引,signals.short_mavg[signals.positions==2.0],“^”,markersize=10,color='m')
#针对AAPL策划“卖出”交易
ax1.plot(signals.ix[signals.positions==-1.0]。索引,signals.short_mavg[signals.positions=-1.0],'v',markersize=10,color=-b')
ax1.plot(signals.ix[signals.positions==-2.0]。索引,signals.short_mavg[signals.positions=-2.0],'v',markersize=10,color=-b')
#用美元绘制股票曲线
ax2=图add_子批次(212,xticklabel=条['Date'],ylabel='组合价值,单位为美元〕)
ax2.设置X刻度线(条['Date'],旋转=45)
返回['total'].plot(ax=ax2,lw=2。)
#根据股票曲线绘制“买入”和“卖出”交易
ax2.plot(returns.ix[signals.positions==1.0]。索引,returns.total[signals.positions==1.0],“^”,markersize=10,color=m”)
ax2.plot(returns.ix[signals.positions==-1.0]。索引,returns.total[signals.positions=-1.0],'v',markersize=10,color='b')
ax2.plot(returns.ix[signals.positions==2.0]。索引,returns.total[signals.positions==2.0],“^”,markersize=10,color=m”)
ax2.plot(returns.ix[signals.positions==-2.0]。索引,returns.total[signals.positions=-2.0],'v',markersize=10,color='b')
#绘制图形
图savefig(“C:/users/gph/desktop/tradingalgorithm/30\u 60EMA\u cross\u backtest.png”)

bars['Date']是从我的计算机上的csv导入的数据框列,但您可以复制它的较小版本,并在示例顶部添加代码段。

因此,经过一点修改后,我自己解决了这个问题。由于某些原因,Pandas 0.17和matplotlib 1.5试图使用
df['column']绘制线条。绘图(ax=ax#)
使我无法控制轴的格式。此外,我使用ax1.setxticklabels(条['Date'],旋转=45)所做的操作是不正确的,因为它将ticklabels设置为整个'Date'列,并且仅根据记号的数量显示前几个

最后,我按照的建议,将'Date'从numpy.datetime64(与matplotlib不友好)转换为float days格式,并使用此值创建一个新列'Dates'。然后创建一个唯一日期列表,并将其转换为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]))) 
剩下的很简单,我对调用
subplot()
的方式做了一些更改,并将sharex=True设置为looks

# 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))

我无法复制您的问题-如果我旋转记号(尝试了标签的
datetime
、字符串和int类型),这一切对我来说都能正常工作。这是一个有点难以帮助,因为你的代码样本不是一个简单的例子。如果您添加一个什么是
条的示例,我们可能会提供帮助。如果您也可以添加导入内容,这将非常有用,这样我们就可以复制并粘贴到编辑器中并运行它。Python版本和matplotlib版本可能也相关。@JRichardSnape Ok很好。我已经编辑了我的问题。确定-花了一点时间找到一个工作组合-使用
CALL
表示符号,使用
10
表示间隔。不得不注释掉
symbol
return
,但它用旋转的x记号标签绘制了价格时间序列,很好:显然还有其他格式问题,但旋转似乎有效?嗯,这很奇怪。所以除了注释掉
return
之外,您不需要做任何更改,我猜您的意思是
信号
而不是
符号
。我试试看。您使用的matplot版本是什么?@JRichardSnape因此,从我到目前为止的测试来看,只要将线数据输入到图形中,问题就会出现。由于正在使用dataframe.plot()绘制这些数据,因此问题可能与matplot无关。令人沮丧的是,自从0.15升级到0.17后,这是我与熊猫的第二个问题。