matplotlib 突出显示日期范围

dfuffjeb  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(101)

我尝试使用以下代码突出显示图的一部分:

import pandas as pd
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
import warnings
warnings.filterwarnings("ignore")

from matplotlib import dates as mdates

start = datetime.date(2020,1,1)
end = datetime.date.today()

stock =  'fb'

data = web.DataReader(stock, 'yahoo', start, end)
data.index = pd.to_datetime(data.index, format ='%Y-%m-%d')
data = data[~data.index.duplicated(keep='first')]
data['year'] = data.index.year
data['month'] = data.index.month
data['week'] = data.index.week
data['day'] = data.index.day
data.set_index('year', append=True, inplace =True)
data.set_index('month',append=True,inplace=True)
data.set_index('week',append=True,inplace=True)
data.set_index('day',append=True,inplace=True)

fig, ax = plt.subplots(dpi=300, figsize =(15,4))
plt.plot(data.index.get_level_values('Date'), data['Close'])
plt.axvspan((datetime(2020,3,12)), (datetime(2020,6,1)), 
            label="Labeled",color="green", alpha=0.3)

字符串
根据文档here,格式应该是matplotlib.pyplot.axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs)。请问如何获得y_min和y_max的值?

locator = mdates.MonthLocator()

formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
plt.show()


我试着让图看起来像这样:

https://datavizpyr.com/highlight-a-time-range-in-time-series-plot-in-python-with-matplotlib/
解释多索引日期时间

xytpbqjk

xytpbqjk1#

import pandas as pd
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
import warnings
warnings.filterwarnings("ignore")

from matplotlib import dates as mdates

start = datetime.date(2020,1,1)
end = datetime.date.today()

stock =  'fb'

data = web.DataReader(stock, 'yahoo', start, end)
data.index = pd.to_datetime(data.index, format ='%Y-%m-%d')
data = data[~data.index.duplicated(keep='first')]
data['year'] = data.index.year
data['month'] = data.index.month
data['week'] = data.index.week
data['day'] = data.index.day
data.set_index('year', append=True, inplace =True)
data.set_index('month',append=True,inplace=True)
data.set_index('week',append=True,inplace=True)
data.set_index('day',append=True,inplace=True)

fig, ax = plt.subplots(dpi=300, figsize =(15,4))
ax.plot(data.index.get_level_values('Date'), data['Close'])
y0,y1 = ax.get_ylim()
offset = data['Close'].max()
new_max = (offset - y0) / (y1 - y0)
ax.axvspan((datetime.datetime(2020,3,12)), (datetime.datetime(2020,6,1)), 
            label="Labeled",color="green", alpha=0.3, ymin=0, ymax=new_max)

plt.show()

字符串


的数据

相关问题