Matplotlib:如何修复意外的x刻度行为

时间:2016-03-31 15:14:25

标签: python matplotlib

我正在制作matplotlib线图,x刻度表现得如此违反直觉。

这是我的数据框:

    year        x       y
0   2012        8154    13496
1   2013        8585    11421
2   2014        10376   10890
3   2015        11720   10714

此代码:

f, ax1 = plt.subplots(1, figsize=(12, 7))

ax1.plot(WholeGrouped['x'],
         marker='o',
         lw=1,
         markersize=9,
         linestyle = '--',
         color='#666666')

ax1.plot(WholeGrouped['y'],
         marker='o',
         lw=3,
         markersize=10,
         color='#12A4DD')

labels = [2012, 2013, 2014, 2015]

ax1.set_xticklabels(labels)

产生这个:

enter image description here

显然,我希望年份标签相对于标记定位。如何将标签分配到正确的位置?

问题的根源在于,当我试图将年份用作x轴时,Matplotlib返回了一些非常奇怪的东西。如下:

f, ax1 = plt.subplots(1, figsize=(12, 7))

ax1.plot(WholeGrouped['x'],
         marker='o',
         lw=1,
         markersize=9,
         linestyle = '--',
         color='#666666')

ax1.plot(WholeGrouped['y'],
         WholeGrouped['year'],
         marker='o',
         lw=3,
         markersize=10,
         color='#12A4DD')

enter image description here

因此我走了标签路线。

将x轴制作多年并将它们适当分开是多么困难!

1 个答案:

答案 0 :(得分:2)

d = [{'year':   2012, 'x':        8154   , 'y': 13496},
     {'year':   2013, 'x':        8585   , 'y': 11421},
     {'year':   2014, 'x':        10376  , 'y': 10890},
     {'year':   2015, 'x':        11720  , 'y': 10714},]

df_so = pd.DataFrame(d)

fig, ax = plt.subplots()
ax.plot('year', 'x', data=df_so)


ax.plot('year', 'y', data=df_so)

ax.xaxis.get_major_formatter().set_useOffset(False)
ax.xaxis.get_major_locator().set_params(integer=True)

enter image description here

您需要mpl 1.5+才能使数据解包工作,否则请使用df_so['x']等。此处的样式是新2.0默认值的预览