每两行绘制条形图

Plotting bar charts by each two rows

我有这样的东西

 id_1 1000
 id_2 200
 id_3  100
 id_4  50

现在因为这是在数据框中,我可以做 df.plot(kind='bar') 然而,这不是我真正想要的,我想要像每两个连续 id 的单独条形图这样的东西。 旋转数据框然后从那里绘制会更好吗? 或者我可以使用一个简洁的循环。我很不擅长使用 matplotlib。

听起来您想要数据切片的条形图。从你的问题中不清楚你想要什么切片,但这里有一些例子:

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

我知道这不是一个完整的答案,但我试图弄清楚你想要什么。我想我会 post 它看看它是否有帮助,但如果我偏离主题,请发表评论,我会删除。

导入所需内容:

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