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

标签 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 轴设为年份并使其适当间隔是多么困难!

最佳答案

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 默认值的预览

关于python - Matplotlib:如何修复意外的 x 刻度行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36337364/

相关文章:

python - pyplot - 无法绘制虚线

python - DeprecationWarning - imp 模块

python - argparse:位置参数的默认值不起作用?

Python 类型错误 : not enough arguments for format string

python - 从 imaplib 获取的电子邮件没有换行符

python - 使用 neo4jrestclient 中的事务从索引中检索节点

python - Matplotlib 与 Google App Engine

python - 使用 pip install Matplotlib 时出现内存错误

python - 带有 X、Y 数据的 Matplotlib 热图

python - 让文本显示在子图图像前面