1 回答

TA貢獻1719條經(jīng)驗 獲得超6個贊
一種方法是將日期設(shè)置為索引。然后,執(zhí)行reindex()從第一個到最后一個日期的所有日期。這將填寫'NaN'(“不是數(shù)字”或“不可用”)對應(yīng)于缺失日期的數(shù)據(jù)。NaN值通常會在繪制的數(shù)據(jù)中創(chuàng)建一個空白點。
我不知道ls='steps'matplotlib 中的選項plot(),但有一個類似的選項step()可以創(chuàng)建步驟圖。(在 matplotlib 之上,pandas 和 seaborn 還構(gòu)建了一些接口來創(chuàng)建這種和許多其他類型的繪圖。)
順便說一句,當在同一個地方繪制多個圖形時,重復(fù)使用同一個圖形通常效果最好ax。plt.subplots()是通過一次調(diào)用創(chuàng)建圖窗和子圖(默認 1 行 1 列)的簡便方法。可以設(shè)置許多選項,其中figsize.
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import dates as mdates
from io import StringIO
data_str = ''' Date Central_SMA Bottom_Central_SMA Top_Central_SMA
0 2020-06-02 97.891667 97.7125 98.070833
1 2020-06-03 98.833333 98.9250 98.741667
2 2020-06-04 98.516667 98.4625 98.570833
3 2020-06-05 98.175000 98.0000 98.350000
4 2020-06-08 98.633333 98.5000 98.766667'''
Graph = pd.read_csv(StringIO(data_str), delim_whitespace=True)
Graph['Date'] = pd.to_datetime(Graph['Date']) # just making sure the 'Date' really is in pandas date format
Graph.set_index('Date', inplace=True)
Graph = Graph.reindex(index=pd.date_range(start=Graph.index[0], end=Graph.index[-1], freq='D'))
fig, ax = plt.subplots(figsize=(12, 5))
ax.step(Graph.index, Graph['Central_SMA'], label='Central SMA')
ax.step(Graph.index, Graph['Top_Central_SMA'], label='Top SMA')
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
ax.legend()
plt.show()
添加回答
舉報