在使用 pandas 绘图方法创建的图表上格式化 x 轴 [英] Format x-axis on chart created with pandas plot method

查看:34
本文介绍了在使用 pandas 绘图方法创建的图表上格式化 x 轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pandas.DataFrame.plot是一种从数据框中绘制数据的便捷方法.但是,我不明白如何使用这种方法格式化轴.例如,

pandas.DataFrame.plot is a convenient method for plotting data from dataframes. However, I don't understand how to format the axes using this method. For example,

import pandas as pd
import datetime

df = pd.DataFrame(index =  [datetime.datetime(2016, 7, 2, 0, 0),
                    datetime.datetime(2016, 8, 6, 0, 0),
                    datetime.datetime(2016, 9, 13, 0, 0),
                    datetime.datetime(2016, 10, 26, 0, 0),
                    datetime.datetime(2016, 11, 2, 0, 0)],
                    data = {'total' : [5, 3, 1, 0, 2]})

df

输出

          total
2016-07-02  5
2016-08-06  3
2016-09-13  1
2016-10-26  0
2016-11-02  2

现在使用熊猫绘图方法绘图:

Now plotting with the pandas plot method:

df.plot(kind='bar')

我希望x轴仅将标签作为月份的三个字母的格式-七月八月九月十月十一月.

I would prefer that the x-axis just have the labels as the three-letter format of month - Jul Aug Sep Oct Nov.

使用pandas plot方法是否可行?还是应该使用matplotlib构建图表?

Is this possible with the pandas plot method or should I build a chart with matplotlib instead?

推荐答案

我发现了将x标签更改为仅月的更简单方法.

I found a simpler way to change the x labels to month only.

import pandas as pd
import datetime

df = pd.DataFrame(index =  [datetime.datetime(2016, 7, 2, 0, 0),
                    datetime.datetime(2016, 8, 6, 0, 0),
                    datetime.datetime(2016, 9, 13, 0, 0),
                    datetime.datetime(2016, 10, 26, 0, 0),
                    datetime.datetime(2016, 11, 2, 0, 0)],
                    data = {'total' : [5, 3, 1, 0, 2]})

ax = df.plot(kind='bar')
x_labels = df.index.strftime('%b')
ax.set_xticklabels(x_labels)

plt.show()

这篇关于在使用 pandas 绘图方法创建的图表上格式化 x 轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆