如何在python中转换month列来绘制条形图?

2024-09-24 00:32:38 发布

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

我有这样一个数据帧。month列的类型为string。 我想做一个从201501到201505的条形图,其中x轴是月份,y轴是总的。x格式类似于2015年1月至2015年2月。那么如何使用python实现呢?谢谢。在

month   total_gmv
201501  NaN
201502  2.824294e+09
201503  7.742665e+09
201504  2.024132e+10
201505  6.705012e+10

Tags: 数据类型string格式nantotal条形图月份
3条回答
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {'month': ['201501', '201502', '201503', '201504', '201505'], 
     'total_gmv': [np.nan, 2.824294e+09, 7.742665e+09, 2.024132e+10, 6.705012e+10]})

df['month'] = pd.to_datetime(df['month'], format='%Y%m').dt.month
df = df.set_index('month')

print df
df.plot(kind='bar')
plt.show()

结果:

^{pr2}$

enter image description here

以前的答复有一些线索,但没有显示详尽的答案。 您必须设置自定义的xtick标签并按如下方式旋转:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {'month': ['201501', '201502', '201503', '201504', '201505'], 
     'total_gmv': [np.nan, 2.824294e+09, 7.742665e+09, 2.024132e+10, 6.705012e+10]})
df['month'] = pd.to_datetime(df['month'], format='%Y%m', errors='ignore')

ax = df.plot(kind='bar')
ax.set_xticklabels(df['month'].dt.strftime('%b, %Y'))
plt.xticks(rotation=0)
plt.show()

enter image description here

您应该使用matplotlib.pyplotcalendar模块。在

import matplotlib.pyplot as plt
import calendar

#change the numeric representation to texts (201501 -> Jan,2015)
df['month_name'] = [','.join([calendar.month_name[int(date[-1:-3]),date[-3:]] for date in df['month']

#change the type of df['month'] to int so plt can read it
df['month'].apply(int)

x = df['month']
y = df['total_gmv']
plt.bar(x, y, align = 'center')

#i'm not sure if you have to change the Series to a list; do whatever works
plt.xticks =(x, df['month_name']) 
plt.show()

相关问题 更多 >