如何在python中绘制条形图

时间:2014-04-10 22:33:09

标签: python numpy matplotlib bar-chart

我想为下面的数据绘制条形图:

4  1406575305  4
4  -220936570  2
4  2127249516  2
5  -1047108451  4
5  767099153  2
5  1980251728  2
5  -2015783241  2
6  -402215764  2
7  927697904  2
7  -631487113  2
7  329714360  2
7  1905727440  2
8  1417432814  2
8  1906874956  2
8  -1959144411  2
9  859830686  2
9  -1575740934  2
9  -1492701645  2
9  -539934491  2
9  -756482330  2
10  1273377106  2
10  -540812264  2
10  318171673  2

第1列是x轴,第3列是y轴。对于相同的x轴值存在多个数据。例如,

4  1406575305  4
4  -220936570  2
4  2127249516  2

这意味着三个条形图用于4个x轴值,每个条形图用标记(中间列中的值)标记。示例条形图如下:     http://matplotlib.org/examples/pylab_examples/barchart_demo.html

我正在使用matplotlib.pyplot和np。感谢..

1 个答案:

答案 0 :(得分:0)

我按照您链接的教程进行操作,但将它们移动到不均匀的数量有点棘手:

import numpy as np
import matplotlib.pyplot as plt

x, label, y = np.genfromtxt('tmp.txt', dtype=int, unpack=True)

ux, uidx, uinv = np.unique(x, return_index=True, return_inverse=True)
max_width = np.bincount(x).max()
bar_width = 1/(max_width + 0.5)

locs = x.astype(float)
shifted = []
for i in range(max_width):
    where = np.setdiff1d(uidx + i, shifted)
    locs[where[where<len(locs)]] += i*bar_width
    shifted = np.concatenate([shifted, where])

plt.bar(locs, y, bar_width)

numbered

如果您愿意,可以使用第二列而不是x:

标记它们
plt.xticks(locs + bar_width/2, label, rotation=-90)

labeled

我会把它们作为练习留给读者(主要是因为我不知道你希望它们如何显示)。

相关问题