Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

python - How to determine the order of bars in a matplotlib bar chart

Suppose we read some data into a pandas data frame:

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

The content looks like this:

enter image description here

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:

enter image description here

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you directly read the key as the index with

In [12]: df = pd.read_csv('data.csv', '', 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:

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...