xytext details in Matplotlibs Annotate

随声附和 提交于 2019-12-24 10:58:13

问题


With the following code I am plotting a candlestick graph and also make use of annotations. I have played arround until I found the right positions for the text, but I still don't understand what the figures xytext=(-15, -27) and xytext=(-17, 20) have to do with their current position.

It is very strange to me. could somebody please explain it to me? Many thanks in advance!
This is what my graph looks like and below is the code:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.finance import candlestick_ohlc
from matplotlib import style
import pandas_datareader
import datetime as dt

style.use('classic')
start = dt.datetime(2017,1,1)
end = dt.datetime(2017,4,1)

def graph(stock):
    ax1 = plt.subplot2grid((1,1), (0,0))
    stock_data = pandas_datareader.DataReader(name=stock, data_source='google', start=start, end=end)
    stock_data.reset_index(inplace=True)
    stock_data['Date'] = stock_data['Date'].map(mdates.date2num)
    candlestick_ohlc(ax1, stock_data.values, width=0.5, colorup='g', colordown='r')

    ax1.annotate('Long',
                 xy=(stock_data['Date'][10], stock_data['Low'][10]),
                 xytext=(-15, -27),
                 textcoords='offset points',
                 arrowprops=dict(facecolor='grey', color='grey'))

    ax1.annotate('Short',
                 xy=(stock_data['Date'][28], stock_data['High'][28]),
                 xytext=(-17, 20),
                 textcoords='offset points',
                 arrowprops=dict(facecolor='grey', color='grey'))

    ax1.annotate('Long',
                 xy=(stock_data['Date'][42], stock_data['Low'][42]),
                 xytext=(-15, -27),
                 textcoords='offset points',
                 arrowprops=dict(facecolor='grey', color='grey'))

    ax1.annotate('Short',
                 xy=(stock_data['Date'][48], stock_data['High'][48]),
                 xytext=(-17, 20),
                 textcoords='offset points',
                 arrowprops=dict(facecolor='grey', color='grey'))

    plt.show()

graph('TSLA')

回答1:


You chose to have the text coordinates in offset points. E.g. xytext=(-17, 20) places the text at 17 points to the left and 20 points to the top from the point which you annotate.

The coordinates may be more obvious when changing the horizontalalignment to "center" in the annotation. annotate( ... , ha="center").

You can then get the result by setting the x coordinate to 0.

ax1.annotate('Long', xy=(stock_data['Date'][10], stock_data['Low'][10]),
                 xytext=(0, -27),
                 textcoords='offset points', ha="center",
                 arrowprops=dict(facecolor='grey', color='grey'))


来源:https://stackoverflow.com/questions/44928011/xytext-details-in-matplotlibs-annotate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!