【问题标题】:Issue Annotating Points With Matplotlib使用 Matplotlib 发布注释点
【发布时间】:2021-07-19 19:21:48
【问题描述】:

我正在使用 Python 和 Matplotlib 编写一个 Jupyter 笔记本脚本,该脚本应该通过 yfinance 包获取指定股票的历史股票价格,并绘制每只股票的波动率与潜在回报的关系。

预期和实际结果可以在here找到。

正如您在第二张图片中看到的那样,股票代码每个点旁边的注释完全缺失。我对 Matplotlib 很陌生,所以我有点茫然。使用的代码如下:

import yfinance as yf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from functools import reduce
from google.colab import files

sns.set()

directory = '/datasets/stocks/'
stocks = ['AAPL', 'MSFT', 'AMD', 'TWTR', 'TSLA']

#Download each stock's 6-month historical daily stock price and save to a .csv
df_list = list()
for ticker in stocks:
    data = yf.download(ticker, group_by="Ticker", period='6mo')
    df = pd.concat([data])
    csv = df.to_csv()
    with open(directory+ticker+'.csv', 'w') as f:
      f.write(csv)

#Get the .csv filename as well as the full path to each file
ori_name = []
for stock in stocks:
  ori_name.append(stock + '.csv')
stocks = [directory + s for s in ori_name]

dfs = [pd.read_csv(s)[['Date', 'Close']] for s in stocks]
data = reduce(lambda left,right: pd.merge(left,right,on='Date'), dfs).iloc[:, 1:]

returns = data.pct_change()
mean_daily_returns = returns.mean()
volatilities = returns.std()

combine = pd.DataFrame({'returns': mean_daily_returns * 252,
                       'volatility': volatilities * 252})

g = sns.jointplot("volatility", "returns", data=combine, kind="reg",height=7)

#Apply Annotations
for i in range(combine.shape[0]):
    name = ori_name[i].replace(',csv', '')
    x = combine.iloc[i, 1]
    y = combine.iloc[i, 0]
    print(name)
    print(x, y)
    print('\n')
    plt.annotate(name, xy=(x,y)) 
    
plt.show()

打印出股票名称和我试图放置注释的相应 x,y 位置显示以下内容:

AAPL.csv
4.285630458382526 0.24836925418906455


MSFT.csv
3.3916453932738966 0.5159276490876817


AMD.csv
6.040090684498841 -0.002179408770566866


TWTR.csv
7.911518867192316 0.8556785016280568


TSLA.csv
9.154424353004579 -0.40596099327336554

除非我弄错了,否则这些是在图表上绘制的确切点。因此,我对为什么没有正确注释文本感到困惑。我认为这与plt.annotate()xycoords 参数有关,但我对不同的坐标系了解不多,无法知道使用哪个坐标系,或者这是否是问题的根本原因。

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 我不是sns.jointplot 的专家,但它有三个子图,所以plt.annotate 不知道将注释放入三个子图中的哪一个。深入研究文档,你应该在jointplot返回的g中找到中心轴的句柄,然后就可以做g.ax.annotate()
  • @JodyKlymak 哇,这令人惊讶的简单,而且工作起来就像一个魅力。非常感谢!

标签: python pandas matplotlib stock


【解决方案1】:

正如@JodyKlymak 在他上面的评论中所说,我的代码问题源于包含多个子图的联合图,导致annotate() 无法知道文本放置基于哪些轴。只需将 plt.annotate() 替换为 g.ax_joint.annotate() 即可轻松解决此问题。

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2012-05-09
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多