python - Issue with rotating x tick labels in matplotlib subplots -


i having issue getting x axis tick labels rotate. have tried following matplotlib documentation axes.set_xticklabels() using ax1.set_xticklables(labels, rotation=45). have tried using plt.setp per this post still havent been able rotate labels. reference code follows:

import matplotlib.pyplot plt import numpy np import pandas pd import datetime   print("enter symbol:") symbol = input() symbol = symbol.upper() print("enter interval:") interval = input() print("you entered: " + symbol)  # obtain minute bars of symbol google finance 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 outer color white ax1 = fig.add_subplot(211, ylabel='price in $') ax1.set_xticklabels(bars['date'], rotation=45)  # plot dia closing price overlaid moving averages bars['close'].plot(ax=ax1, color='r', lw=2.) signals[['short_mavg', 'long_mavg']].plot(ax=ax1,lw=2.)  # plot "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 "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 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 "buy" , "sell" trades against 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 figure fig.savefig("c:/users/gph/desktop/tradingalgorithm/30_60ema_cross_backtest.png") 

bars['date'] dataframe column imported csv on machine, replicate smaller version of segment of code in top of example.

so after bit of tinkering figured out on own. reason pandas 0.17 , matplotlib 1.5 trying plot lines df['column'].plot(ax=ax#) prevents me being able control formatting of axis. furthermore doing ax1.set_xticklabels(bars['date'], rotation=45) incorrect in setting ticklabels entirety of 'date' column , displaying first few based on number of ticks.

what ended doing following advice of this post, converting 'date' numpy.datetime64 (not friendly matplotlib) float days format, , create new column 'dates' value. list of unique days created , converted iso date format.

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

the rest pretty simple, made few changes way called subplots() , set sharex=true looks.

# plot 2 subplots assess trades , equity curve.  fig, (ax1, ax2) = plt.subplots(, 1, sharex=true) fig.patch.set_facecolor('white') # set outer color white ax1.set_ylabel('price in $') # plot dia closing price overlaid 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 "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 "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 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 "buy" , "sell" trades against 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 figure plt.tight_layout() plt.show() fig.savefig("c:/users/gph/desktop/tradingalgorithm/{}_{}ema_cross_backtest.png".format(short_window, long_window)) 

it worked!


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -