如何确定Matplotlib条形图中的条形顺序 [英] How to determine the order of bars in a matplotlib bar chart
问题描述
假设我们将一些数据读入pandas数据框中:
Suppose we read some data into a pandas data frame:
data1 = pd.read_csv("data.csv", "\t")
内容如下:
然后定义一个函数,该函数应该为我们提供水平条形图,条形图的长度代表值,条形图由键标记.
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)
然后我们像这样调用plot函数:
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?
假设我们希望条以特殊顺序显示,例如[C, A, D, F, E, B]
,我们该如何执行呢?
Suppose we want the bars in a special order, say [C, A, D, F, E, B]
, how can we enforce this?
推荐答案
我修改了条形图的原始版本.为了指定条的顺序,我使用了通过ii列设置的索引:
I modified original version of barchart. To specify order of bars I am using index set via ii column:
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()
这篇关于如何确定Matplotlib条形图中的条形顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!