python - 删除 x 轴覆盖不需要的索引标签
问题描述
我正在使用下面的代码来绘制一个图形。如图所示,由于某种原因,X 轴上不需要的索引标签覆盖了日期。如何将它们移除?
使用python2.7,matplotlib==2.2.4,pandas==0.23.1
def _create_image(x_labels, y_labels, title):
df = pd.DataFrame({'date': x_labels, 'count': y_labels})
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True, drop=True)
fig, ax = plt.subplots(figsize=(13, 5), sharex='all')
df.plot(kind='line', ax=ax, marker='o', markerfacecolor='green', markersize=5, legend=False)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=3))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d %b'))
plt.xlabel('Dates')
plt.ylabel('Count')
plt.title(title)
plt.savefig('/tmp/tmp_pic.png')
熊猫DF输入:
date count
2019-04-02 247640
2019-04-03 429405
2019-04-04 168808
2019-04-05 227930
2019-04-06 70628
2019-04-07 141943
2019-04-08 143102
2019-04-09 123590
2019-04-10 285473
2019-04-11 203974
2019-04-12 56283
2019-04-13 52168
2019-04-14 58632
2019-04-15 112912
2019-04-16 59196
2019-04-17 30239
2019-04-18 112585
2019-04-19 39416
2019-04-20 99569
2019-04-21 55780
2019-04-22 56596
2019-04-23 67868
2019-04-24 40587
2019-04-25 47498
2019-04-26 22111
2019-04-27 48653
2019-04-28 14990
2019-04-29 49540
2019-04-30 39691
解决方案
通常,您不能将matplotlib.dates
代码用于 pandas 日期时间图。matplotlib.dates
但是您可以通过参数制作兼容的熊猫图x_compat=True
。
df.plot(..., x_compat=True)
推荐阅读
- swift - 使自定义 get {} set{} 像动态代理/快捷方式一样工作,以访问 Array 中的不同对象。(斯威夫特用户界面)
- php - 如何在没有会话或文件包含的情况下从我的注册文件中获取密码哈希 $string 到登录文件
- python - 如何在熊猫中精确创建垃圾箱
- nest - 如何使用 Fastify 为 Nest 添加自定义内容类型解析器
- excel - 在 Excel 中比较同一列内的多个单元格
- c# - 制作日历 - 从星期日开始的月份会被剪掉第一周
- websocket - WebSocket:如何使用 DataPower 将 websocket 连接从主集群切换到备用集群?
- java - Spring Boot yaml 属性布尔值无法识别
- python-3.x - xgb.train(): TypeError: float() argument must be a string or a number, not 'DMatrix'
- parsing - 解析平台 liveQuery 观察