gpt4 book ai didi

python - 两个 Pandas 系列的散点图,按日期着色并带有图例

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:43 25 4
gpt4 key购买 nike

我正在研究 Pandas 系列格式的金融时间序列。为了比较两个系列,我做了一个散点图,为了可视化散点图中的时间演变,我可以给它们着色。这一切都很好。

我的问题与显示颜色的图例有关。我希望图例显示颜色对应的日期/年份,而不仅仅是像现在这样的数据条目的索引。但我无法做到这一点,也无法在 stackoverflow 上找到这样的问题。

我知道时间序列知道日期,如果您只绘制时间序列,x 轴将显示日期。

我的代码是

from pandas_datareader import data as web
import matplotlib.pyplot as plt
import pandas as pd

#Download data
start = '2010-1-1'
end = '2016-10-1'
AAPL = web.DataReader('AAPL', 'yahoo', start=start, end=end)['Adj Close']
TSLA = web.DataReader('GOOG', 'yahoo', start=start, end=end)['Adj Close']

#Scatterplot
plt.scatter(AAPL, TSLA, alpha=.4, c=range(len(AAPL)))
plt.colorbar()
plt.xlabel("AAPL")
plt.ylabel("TSLA")
plt.grid()
plt.show()

此代码生成此图: Scatterplot with colours and legend

谢谢

最佳答案

虽然可能有一个更简单的答案(有人吗?),但对我来说,最直接的方法是手动更改颜色栏刻度。

在调用 plt.show() 之前尝试以下操作:

clb = plt.gci().colorbar # get the colorbar artist
# get the old tick labels (index numbers of the dataframes)
clb_ticks = [int(t.get_text()) for t in clb.ax.yaxis.get_ticklabels()]
# convert the old, index, ticks into year-month-day format
new_ticks = AAPL.index[clb_ticks].strftime("%Y-%m-%d")
clb.ax.yaxis.set_ticklabels(new_ticks)

请注意,strftime 似乎并未在 0.18 之前的 pandas 版本中实现。在这种情况下,您必须将 .strftime("%Y-%m-%d") 替换为 .apply(lambda x: x.strftime('%Y-%m -%d')) 如所解释的 here .

clb-ymd_labels-pandas

关于python - 两个 Pandas 系列的散点图,按日期着色并带有图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40061493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com