条形图(高度)不相等

时间:2017-05-16 04:04:33

标签: python csv matplotlib

我尝试了一个条形图,从我的csv文件及其工作中添加了一个值标签,但我遇到了一个问题,为什么条形图的高度不相等?

CSV文件: CPU_5_SEC; CPU_1_MIN; CPU_5_MIN; 27; 17; 16;

代码:

import numpy as np
import matplotlib.pyplot as plt

N = 3
men_std=(0,1,2)

data = np.loadtxt('show-process-cpu.csv',dtype=bytes, delimiter=';', usecols=(0,1,2))
utilization= data[1]

label = np.loadtxt('show-process-cpu.csv',dtype=bytes, delimiter=';', usecols=(0,1,2)).astype(str)
my_xticks = label[0]

ind = np.arange(N)
width = 0.40

rects = plt.bar(ind, utilization, width ,men_std,color='r',)

plt.title("Cpu Utilization\n ('%') ")
plt.xticks(ind,my_xticks)

def autolabel(rects):

    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x() + rect.get_width()/2,height,
                '%d' % int(height),
                ha='center', va='bottom')

autolabel(rects)

plt.show()

1 个答案:

答案 0 :(得分:0)

你的ax.bar第二个参数需要是一个整数数组。我还删除了men_std=(0,1,2)参数和定义,因为这样可以将条形图绘制在不同的高度。

import numpy as np
import matplotlib.pyplot as plt

N = 3

data = np.loadtxt('show-process-cpu.csv',dtype=bytes, delimiter=';', usecols=(0,1,2))

my_xticks = data[0]
utilization = data[1]
utilization_int = [int(x) for x in utilization]

ind = np.arange(N)
width = 0.40

fig, ax = plt.subplots()
rects1 = ax.bar(ind, utilization_int, width,color='r',)

ax.set_title("Cpu Utilization\n ('%') ")
ax.set_xticks(ind)
ax.set_xticklabels(my_xticks)

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2,height,
                '%d' % int(height),
                ha='center', va='bottom')

autolabel(rects1)
plt.show()

enter image description here