更改了 Pandas '.bar' 图中的刻度频率,但弄乱了实际的条形图

Changed frequency of ticks in Pandas '.bar' plot, but messed up the actual bars

你的自我隔离怎么样了?

开采岩石,因为我正在 Python 中通过可视化进行钻探。然而,最近我 运行 遇到了一个问题。

我认为 Pandas 中的 .plot.bar() 具有不常见的 x 轴格式(这有点证实我在询问之前阅读过)。我有每月频率的价格数据,所以我应用了一个修复程序,在条形图中仅显示年度刻度:

fig, ax = plt.subplots()
ax.bar(btc_returns.index, btc_returns)

ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

其中 btc_returns 是索引中包含日期时间的 Series 对象。

我得到的输出很奇怪。这是我的预期与最终结果的屏幕截图。

我试图找到解决这个问题的方法,但没有成功。你们能帮帮我吗?谢谢!一如既往地欢迎批评:)

  • 使用来自 Yahoo Finance: Bitcoin USD
  • 的股票价值数据
  • 从技术上讲,您可以在开始时执行 pd.to_datetime(btc.Date).dt.date,但 resample 将不起作用,这就是为什么 btc_monthly.index.date 作为第二步完成的原因。
  • resample 可以在不同时期发生(例如 2M = 每两个月)

加载并转换数据

import pandas as pd
import matplotlib.pyplot as plt

# load data
btc = pd.read_csv('data/BTC-USD.csv')

# Date to datetime
btc.Date = pd.to_datetime(btc.Date)

# calculate daily return %
btc['return'] = ((btc.Close - btc.Close.shift(1))/btc.Close.shift(1))*100

# resample to monthly and aggregate by sum
btc_monthly = btc.resample('M', on='Date').sum()

# set the index to be date only (no time)
btc_monthly.index = btc_monthly.index.date

情节

btc_monthly.plot(y='return', kind='bar', figsize=(15, 8))
plt.show()

剧情双月刊

btc_monthly = btc.resample('2M', on='Date').sum()  # instead of 'M'
btc_monthly.index = btc_monthly.index.date

btc_monthly.plot(y='return', kind='bar', figsize=(15, 8), legend=False)
plt.title('Bitcoin USD: Bimonthly % Return')
plt.ylabel('% return')
plt.xlabel('Date')
plt.show()

而我的解决方案是这样的:

fig, ax = plt.subplots(figsize=(15,7))
ax.bar(btc_returns.index, btc_returns.returns.values, width = 1)

其中btc_returns是一个带有returns比特币的DataFrame。我认为 .values 使条形图正确读取日期时间输入。对于 'missing' 条 - 它们的分辨率太小了,所以我将 width 设置为“1”。