如何确定matplotlib bar ch中条的顺序

2024-06-07 19:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们将一些数据读入pandas数据框:

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

内容如下:

enter image description here

然后定义一个函数,它应该给我们一个水平条形图,其中条形图的长度表示值,条形图用键标记。

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函数:

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

这给了我们以下的情节:

enter image description here

现在,是什么决定了酒吧的顺序?

假设我们想要一个特殊的顺序,比如说[C, A, D, F, E, B],我们如何执行这个?


Tags: csvthe数据函数pos内容pandasread
2条回答

我修改了条形图的原始版本。要指定条的顺序,我正在使用通过I I列设置的索引:

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

如果直接用

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

可以使用ix以不同的顺序获取索引,并使用df.plot绘制索引:

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

barh_example.png

(注意,数据中没有给出F,但您将其作为示例给出)

相关问题 更多 >

    热门问题