Issue
I have the following snippit of code:
data.plot(y='Close', ax = ax)
newdates = exceptthursday.loc[start:end]
for anotate in (newdates.index + BDay()).strftime('%Y-%m-%d'):
ax.annotate('holliday', xy=(anotate, data['Close'].loc[anotate]), xycoords='data',
xytext=(-30, 40), textcoords='offset points',
size=13, ha='center', va="baseline",
bbox=dict(boxstyle="round", alpha=0.1),
arrowprops=dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1));
This produces a plot which looks like this:
As you can see i have explicitly mentioned the xytext
, this makes the "bubbles" messy as at some locations they overlap which makes it hard to read. Is there any way it can be "auto - placed" so that they are not overlapping. Such as some of the "bubbles" are above and below the plot line in such a way that they do not overlap.
Solution
Because of the small amount of holiday data used, the degree of overlap in the annotations will seem less effective because of the small amount of overlap in the annotations, but the gist of the answer is that the issue could be improved slightly by varying the position of the annotations according to the index.
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from pandas_datareader import data as web
from pandas.tseries.holiday import USFederalHolidayCalendar as calendar
data = web.DataReader('fb', 'yahoo')
cal = calendar()
holidays = cal.holidays(start=data.index.min(), end=data.index.max())
data['Holiday'] = data.index.isin(holidays)
holiday = data[data['Holiday'] == True]
fig = plt.figure(figsize=(16,6))
ax = fig.add_subplot(111)
ax.plot(data.index, data.Close)
for i,x,y in zip(range(len(holiday)),holiday.index, holiday.Close):
if i % 2 == 0:
ax.annotate('holliday', xy=(x,y), xycoords='data',
xytext=(-30, 40), textcoords='offset points',
size=13, ha='center', va="baseline",
bbox=dict(boxstyle="round", alpha=0.1),
arrowprops=dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1))
else:
ax.annotate('holliday', xy=(x,y), xycoords='data',
xytext=(30, -40), textcoords='offset points',
size=13, ha='center', va="baseline",
bbox=dict(boxstyle="round", alpha=0.1),
arrowprops=dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1))
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=None, interval=3, tz=None))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
ax.tick_params(axis='x', labelrotation=45)
Answered By - r-beginners
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.