我正在尝试使用 'pandas.tseries.index.DatetimeIndex'
绘制 pandas series
。 x 轴标签顽固地重叠,即使有几个建议的解决方案,我也无法使它们美观。
我试过stackoverflow solution suggesting to use autofmt_xdate
但这没有帮助。
我也尝试了plt.tight_layout()
的建议,但没有效果。
ax = test_df[(test_df.index.year ==2017) ]['error'].plot(kind="bar")
ax.figure.autofmt_xdate()
#plt.tight_layout()
print(type(test_df[(test_df.index.year ==2017) ]['error'].index))
更新:我使用条形图是一个问题。常规时间序列图显示管理良好的标签。
最佳答案
pandas 条形图是一个分类图。它在刻度上的整数位置处为每个索引显示一个条形。因此,第一个条位于位置 0,下一个条位于位置 1,依此类推。标签对应于数据帧的索引。如果您有 100 个条形,那么您最终将得到 100 个标签。这是有道理的,因为 pandas 无法知道这些数据是否应该被视为类别或序数/数字数据。
如果您使用普通的 matplotlib 条形图,它将以数字方式处理数据帧索引。这意味着条形图的位置根据实际日期而定,标签根据自动报价器放置。
import pandas as pd
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=42).tolist()
df = pd.DataFrame(np.cumsum(np.random.randn(42)),
columns=['error'], index=pd.to_datetime(datelist))
plt.bar(df.index, df["error"].values)
plt.gcf().autofmt_xdate()
plt.show()
这样做的好处是可以使用 matplotlib.dates
定位器和格式化程序。例如。使用自定义格式标记每月的第一天和第十五天,
import pandas as pd
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=93).tolist()
df = pd.DataFrame(np.cumsum(np.random.randn(93)),
columns=['error'], index=pd.to_datetime(datelist))
plt.bar(df.index, df["error"].values)
plt.gca().xaxis.set_major_locator(mdates.DayLocator((1,15)))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%d %b %Y"))
plt.gcf().autofmt_xdate()
plt.show()
关于python - 日期时间 x 轴 matplotlib 标签导致不受控制的重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49231052/