Matplotlib 显示 x 轴标签不完整;如何防止重叠?

我已经编写了显示 MACD 指标图的代码。我在这里做了什么:


import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.dates as mdates


df = pd.read_csv(#stock_chart)

df = df.rename(columns={"<DTYYYYMMDD>":"Date"})

df['Date'] = pd.to_datetime(df['Date'].astype(str), format="%Y%m%d")

print(df.head())

#seting index for graph

df = df.set_index(df['Date'].values)

print(df.head())

我的数据框的头部是:

http://img3.mukewang.com/64916e3f0001cc7b06520196.jpg

#Macd

S_term = 12

L_term = 26

s_ema = df.close.ewm(span=S_term, adjust=False).mean()

l_ema = df.close.ewm(span=L_term, adjust=False).mean()

#calculate MACD

macd = s_ema - l_ema


signal_term = 9

signal_line = macd.ewm(span= signal_term, adjust=False).mean()


#plot the graphs

plt.figure(figsize=(100,10)) #width = 12.2in, height = 4.5

plt.plot(df.index, macd, label='macd', color = 'red')

plt.plot(df.index, signal_line, label='Signal Line', color='blue')

plt.tight_layout()


plt.xticks(rotation=0)

plt.legend(loc='upper left')

plt.show()

最后,我得到了这个:

http://img.mukewang.com/64916e4b0001613a06490230.jpg

不管怎样,问题是尽管行索引标签是这样的:2020-08-19 or "%Y%m%d"图形标签不完整,如果我重新排序,数据就会相互重叠。我需要做什么 ?



潇湘沐
浏览 135回答 1
1回答

茅侃侃

您可以使用Date locators和Date formatters。import numpyimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport pandasN = 192numpy.random.seed(N)dates = pandas.date_range('1/1/2004', periods=N, freq='m')df = pandas.DataFrame(    data=numpy.random.randn(N),     index=dates,    columns=['A'])fig, ax = plt.subplots()ax.plot(df.index, df['A'])ax.xaxis.set_major_locator(mdates.YearLocator())ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))fig.autofmt_xdate()plt.show()interval是每次迭代之间的间隔。例如,如果interval=2,标记每两次出现一次。import numpyimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport pandasN = 192numpy.random.seed(N)dates = pandas.date_range('1/1/2004', periods=N, freq='m')df = pandas.DataFrame(    data=numpy.random.randn(N),     index=dates,    columns=['A'])fig, ax = plt.subplots()ax.plot(df.index, df['A'])ax.xaxis.set_major_locator(mdates.MonthLocator(interval=5))ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))fig.autofmt_xdate()plt.show()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python