在用pandas plot方法创建的图表上设置x轴格式

2024-05-14 07:32:34 发布

您现在位置:Python中文网/ 问答频道 /正文

plot是一种方便的从数据帧绘制数据的方法。但是,我不知道如何使用这种方法格式化轴。例如

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

现在使用pandas plot方法绘制:

df.plot(kind='bar')

example bar chart

我希望x轴上的标签是3个字母的格式,即月-七月-八月-九月-十月-十一月

使用pandas plot方法是否可行,或者我应该用matplotlib构建一个图表?


Tags: 数据方法importdataframepandasdfdatadatetime
2条回答

我找到了一种更简单的方法将x标签改为仅限月份。

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()

example chart

如果要将图形显示为分类条形图,即独立于实际日期的等距条形图,可以重新格式化xticklabels

f = lambda x: datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S').strftime('%b')
ax.set_xticklabels([ f(x.get_text()) for x in ax.get_xticklabels()])

其中%b是月份的缩写,ax是绘图的轴。

完整示例:

import pandas as pd
import datetime
import matplotlib.pyplot as plt

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')

f = lambda x: datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S').strftime('%b')
ax.set_xticklabels([ f(x.get_text()) for x in ax.get_xticklabels()])

plt.show()

enter image description here

相关问题 更多 >

    热门问题