2016-12-21 39 views
1

我有這樣的數據框。月份列是字符串類型。 我想製作201501至201505的條形圖,x軸爲月份,y軸爲total_gmv。 x格式就像2015年1月,2015年2月。那麼如何使用python實現它?謝謝。如何使python中的月份欄轉換爲條形圖?

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

回答

0

上一頁答覆有一些線索,但它並沒有展現無遺答案。 你必須設置自定義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

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

檢查here for more

1

您應該使用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() 
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 

enter image description here

+0

感謝。其實我想要把x軸標記爲2015年1月15日feb.2015 – yanachen

相關問題