pandas 如何确定 matplotlib 条形图中的条形顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20548727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine the order of bars in a matplotlib bar chart
提问by clstaudt
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:
然后我们像这样调用 plot 函数:
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],我们如何强制执行此操作?
采纳答案by lowtech
I modified original version of 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()
回答by bmu
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 ixto 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>


(Note that F is not given in the data, but you gave it as an example)
(注意数据中没有给出F,只是你举了个例子)

