2

価格とボリュームを含む DataFrame があるとします (金融を考えてください)。

各価格ポイントにその価格ポイントのボリュームでラベルを付ける最良の方法は何ですか?

                  Price   Volume
2013-04-10 04:46  1300      19
2013-04-10 04:47  1305      20
2013-04-10 04:48  1302       6
2013-04-10 04:49  1301      10
4

1 に答える 1

2

ここに1つの可能な実装があります

私は以下をインポートしました:

import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt

これでデータを再作成できます

ind = pd.date_range(start=dt.datetime(2013, 4, 10, 4, 46),
                      periods=4, freq='Min')

data = pd.DataFrame([[1200, 19], [1302, 20], [1302, 6], [1301, 10]],
                    index=ind, columns=['Price', 'Volume'])

ここで、annotate_plot 関数を定義します。docstring には、それが何をしているかを把握するのに十分な情報が含まれている必要があります。

def annotate_plot(frame, plot_col, label_col, **kwargs):
    """
    Annotate the plot of a given DataFrame using one of its columns

    Should be called right after a DataFrame or series plot method,
    before telling matplotlib to show the plot.

    Parameters
    ----------
    frame : pandas.DataFrame

    plot_col : str
        The string identifying the column of frame that was plotted

    label_col : str
        The string identifying the column of frame to be used as label

    kwargs:
        Other key-word args that should be passed to plt.annotate

    Returns
    -------
    None

    Notes
    -----
    After calling this function you should call plt.show() to get the
    results. This function only adds the annotations, it doesn't show
    them.
    """
    import matplotlib.pyplot as plt  # Make sure we have pyplot as plt

    for label, x, y in zip(frame[label_col], frame.index, frame[plot_col]):
        plt.annotate(label, xy=(x, y), **kwargs)

この関数を使用して、ラベル付きの基本的なプロットを実行できるようになりました

data.Price.plot(marker='*')
annotate_plot(data, 'Price', 'Volume')
plt.show()

plt.annotate() に直接行く annotate_plot 関数を介して任意の引数を渡すこともできます。これらの引数のほとんどは、この回答から取られたことに注意してください。

bbox = dict(boxstyle='round,pad=0.5', fc='green', alpha=0.3)
ha = 'right'
va = 'bottom'
arrowprops = dict(arrowstyle='->', connectionstyle='arc3,rad=0')
xytext = (-20, 20)
textcoords = 'offset points'

data.Price.plot(marker='*')
annotate_plot(data, 'Price', 'Volume', bbox=bbox, ha=ha, va=va, 
              xytext=xytext, textcoords=textcoords)

plt.show()
于 2013-04-17T18:12:46.520 に答える