2017-05-16 40 views
1

我嘗試了一個條形圖,在我的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() 
+0

你有沒有刪除您的評論我的回答?我被通知了,但現在它消失了。請讓我知道它是否有效,如果是,請接受答案。 –

+0

對不起,回覆遲了:),我試了,它的工作,謝謝:) –

+0

np!我很欣賞它,但是在我們這裏,我們主要感謝正確/最好的答案[通過接受它](https://meta.stackexchange.com/a/5235),它會獎勵海報並告訴其他人這個問題已經解決。 –

回答

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