2015-03-03 360 views
0

我有這樣的事情繪製條形圖

id_1 1000 
id_2 200 
id_3 100 
id_4 50 

現在,因爲這是在數據幀我可以做df.plot(KIND =「酒吧」) 然而,這並不是我真正想要的我想爲每兩個連續的ID分開單獨的條形圖。 旋轉數據框然後從那裏繪圖會更好嗎? 還是有一個整潔的循環,我可以使用。我在使用matplotlib時很不好。

+0

請您詳細說明一下嗎?也許提供一個你想到的東西的草圖? [條形圖演示](http://matplotlib.org/examples/api/barchart_demo.html)已分組條形。 – Schorsch 2015-03-03 14:21:04

+0

請澄清,輸入數據究竟是什麼(不確定,如果'id_1'意味着一個字符串或一些符號值)以及您想要繪製哪些條形圖(例如,顯示每個圖表的nameo以指定的x值和y值)值)。 – 2015-03-03 14:45:01

+0

1月你的答案正是我想要的 – 2015-03-04 14:47:27

回答

1

進口所需要的:

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

創建數據繪製:

>>> data = [10, 12, 8, 44, 34, 18] 
>>> idx = ["a", "b", "c", "d", "e", "f"] 
>>> ser = pd.Series(data, index=idx) 
>>> ser 
a 10 
b 12 
c  8 
d 44 
e 34 
f 18 
dtype: int64 

最後創建子系列,並繪製出來

>>> # how many bar charts we expect 
>>> numofcharts = len(ser)/2 

>>> # prepare axes for subplots (1 row, numofcharts columns one per bar chart) 
>>> fig, axs = plt.subplots(1, numofcharts) 

>>> for graphi in range(numofcharts): 
>>>  starti = 2*graphi 
>>>  # create subseries one for each subchart 
>>>  subser = ser[starti:starti+2] 
>>>  # print subseries, to see, what we are going to plot 
>>>  print subser 
>>>  # plot subseries as bar subchart 
>>>  subser.plot(ax=axs[graphi], kind="bar") 
a 10 
b 12 
dtype: int64 
c  8 
d 44 
dtype: int64 
e 34 
f 18 
dtype: int64 

,使劇情出現:

>>> plt.show() 

3 subplots with barcharts

0

這聽起來像你想要條形圖的數據切片。從你的問題,目前尚不清楚你想要什麼片,但這裏有一些例子:

import pandas as pd 

# Generate some fake data 
df = pd.DataFrame({'x':['id_{}'.format(i) for i in range(10)], 
       'y':np.random.uniform(size=10)}) 
  • 情節每隔ID從1開始(所以1,3,5 ...)

    df[1::2].plot(kind='bar') 
    
  • 情節只是連續兩個ID的

    df[0:2].plot(kind='bar') 
    
  • 上的最後一個變種:劇情連續兩個ID的所有數據

    for i in range(0, len(df), 2): 
        df[i:i+2].plot(kind='bar') 
    

我知道這是不是一個完整的答案,但我試圖找出你想要的東西的行。我想我會張貼它看看它是否有幫助,但如果我的主題很好,請留言,我會刪除。