我有这样的数据框。月份列是字符串类型。 我想制作201501到201505的条形图,x轴是月,而y轴是total_gmv。 x格式就像2015年2月2015年1月。那么如何使用python实现它呢?感谢。
month total_gmv
201501 NaN
201502 2.824294e+09
201503 7.742665e+09
201504 2.024132e+10
201505 6.705012e+10
答案 0 :(得分:2)
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()
结果:
total_gmv
month
1 NaN
2 2.824294e+09
3 7.742665e+09
4 2.024132e+10
5 6.705012e+10
答案 1 :(得分:1)
你应该能够强制月份为时间戳,然后将其设置为索引并绘制它。
df['month'] = pd.to_datetime(df.month)
ax = df.set_index('month').plot(kind='bar')
您可能需要更改日期格式。
import matplotlib.dates as mdates
ax.xaxis.set_major_formatter= mdates.DateFormatter('%b, %Y')
答案 2 :(得分:1)
您应该使用matplotlib.pyplot
和calendar
模块。
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()
答案 3 :(得分:1)
之前的回复有一些线索,但它没有显示详尽的答案。 您必须设置自定义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()