如何在Python中绘制柱状图

1 投票
1 回答
1084 浏览
提问于 2025-04-18 02:16

我想为下面的数据画一个柱状图:

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

第一列是x轴,第三列是y轴。对于同一个x轴的值,可能会有多个数据。例如:

4  1406575305  4
4  -220936570  2
4  2127249516  2

这意味着在x轴为4的地方会有三根柱子,每根柱子上都有标签(也就是中间那一列的值)。这个柱状图的样子大概是这样的: http://matplotlib.org/examples/pylab_examples/barchart_demo.html

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

1 个回答

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

我就把这两个都留给读者自己去做(主要是因为我不知道你想让它们怎么显示)。

撰写回答