Xlabel未与Matplotlib时间轴上的点对齐

时间:2018-07-08 20:35:12

标签: matplotlib

我在SO上找到的最近的帖子如下(Date ticks and rotation in matplotlib),但仍然不能解决我的问题。我需要调整年份以使其直接显示在红色方框的下方。我已经尝试过自动套用格式和对齐关键字,但是没有任何效果。有人可以证明我在做什么错吗?

.smallTableContainer {
  position: relative;
  display: none;
  height: auto;
  overflow: hidden;
}

.weekdayHeader {
  background: #bc4b51;
  color: #efefef;
  font-size: 18pt;
  padding: 10px 0px;
}

.sessions {
  padding: 0;
}

.className {
  float: left;
  display: inline-block;
  color: #1e1e1e;
  font-size: 13pt;
  padding-left: 10px;
}

.classTime {
  float: right;
  display: inline-block;
  color: #1e1e1e;
  font-size: 12pt;
  padding-right: 10px;
}

日期列表是通过从各种数据框中提取相关行而获得的,这些值已转换为datatime格式。

My timeline

1 个答案:

答案 0 :(得分:1)

在代码中,您仅设置了xticklabels,但让matplotlib找出了xtick的位置。默认设置是产生等距的xticks,这不是您想要的。如果在设置ax.set_xticks(dates)之前添加了行xticklabels,则会得到所需的内容:

from matplotlib import pyplot as plt
import pandas as pd

dates = pd.to_datetime(pd.Series(['1916', '1938', '1993', '2009', '2017']),format='%Y')
dates = [d for d in dates]

texts = ['1st movie released','1st movie directed by woman','1st Best Director nomination','Best Director won',
     '2nd Best Director Nomination']

fig, ax = plt.subplots(figsize=(14,1))
ax.plot((dates[0],dates[-1]),(0,0),'k',alpha=0.3)

for i, (text,date) in enumerate(zip(texts,dates)):
    ax.scatter(date,0,marker='s', s=100,color='crimson')
    ax.text(date,0.01,text,rotation=45,va="bottom",fontsize=14)

ax.set_xticks(dates)
ax.set_xticklabels([i.year for i in dates])
ax.tick_params(axis='x', which='both',length=0)

ax.set_ylim([-0.01,0.01])

ax.yaxis.set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.grid('off')
ax.patch.set_facecolor('white')

fig.subplots_adjust(bottom=0.2,top=0.9)
ax.get_yaxis().set_ticklabels([])
plt.savefig('align_years.png', bbox_inches='tight')

最终图像(经过一些代码调整,并使用savefig而不是show)现在看起来像这样:

result of the above code

希望这会有所帮助。