每两行绘制条形图

时间:2015-03-03 10:56:55

标签: python pandas matplotlib

我有类似的东西

 id_1 1000
 id_2 200
 id_3  100
 id_4  50

现在因为这是在数据帧中我可以做df.plot(kind =' bar') 然而,这不是我真正想要的,我想要每两个连续id的单独条形图。 是否更好地转动数据框,然后从那里进行绘图? 或者我可以使用一个整洁的循环。我使用matplotlib非常糟糕。

2 个答案:

答案 0 :(得分:1)

听起来你想要条形图来分析数据。从你的问题来看,它并不清楚你想要的切片,但这里有一些例子:

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)})
  • 从1开始绘制每个其他ID(所以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')
    

我知道这不是一个完整的答案,但我试图找出你想要的东西。我想我会发布它以查看它是否有帮助,但只要留下评论,如果我的话题很好,我会删除。

答案 1 :(得分: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

相关问题