简体   繁体   English

如何确定matplotlib条形图中条形的顺序

[英]How to determine the order of bars in a matplotlib bar chart

Suppose we read some data into a pandas data frame: 假设我们将一些数据读入pandas数据框:

data1 = pd.read_csv("data.csv", "\t")

The content looks like this: 内容如下:

在此输入图像描述

And then define a function which should give us a horizontal bar chart, where the bar lengths represent values and the bars are labelled with the keys. 然后定义一个函数,它应该给我们一个水平条形图,其中条形长度代表值,条形用键标记。

def barchart(data, labels):
    pos = arange(len(data))+.5    # the bar centers on the y axis
    barh(pos, data, align='center', height=0.25)
    yticks(pos, labels)

Then we call the plot function like this: 然后我们调用这个绘图函数:

barchart(data1["val"], data1["key"])

which gives us the following plot: 这给了我们以下情节:

在此输入图像描述

Now, what determines the order of the bars? 现在,是什么决定了酒吧的顺序?

Suppose we want the bars in a special order, say [C, A, D, F, E, B] , how can we enforce this? 假设我们想要特殊顺序的条形,比如[C, A, D, F, E, B] ,我们如何强制执行此操作?

If you directly read the key as the index with 如果你直接读取键作为索引

In [12]: df = pd.read_csv('data.csv', '\t', index_col='key')

In [13]: df
Out[13]: 
     val
key     
A    0.1
B    0.4
C    0.3
D    0.5
E    0.2

you can use ix to get the index in a different order and plot it using df.plot : 您可以使用ix以不同的顺序获取索引并使用df.plot绘制它:

In [14]: df.ix[list('CADFEB')].plot(kind='barh')
Out[14]: <matplotlib.axes._subplots.AxesSubplot at 0x530fa90>

barh_example.png

(Note that F is not given in the data, but you gave it as an example) (注意数据中没有给出F,但你给它作为例子)

I modified original version of barchart. 我修改了barchart的原始版本。 To specify order of bars I am using index set via ii column: 要指定条形的顺序,我使用通过ii列设置的索引:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def barchart(data, labels):
    pos = np.arange(len(data)) + 0.5  # the bar centers on the y axis
    plt.barh(pos, data.sort_index(), align='center', height=0.25)
    plt.yticks(pos, labels.sort_index())

data1 = pd.DataFrame({'key': list('ABCDE'), 'val': np.random.randn(5)})

new_keys = list('EDACB')
data1['ii'] = [new_keys.index(x) for x in data1.key]

data1 = data1.set_index('ii')
barchart(data1["val"], data1["key"])
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM