2010-09-29 96 views
4

如何繪製這種數據的直方圖數據,的Python:從一個txt文件

10 apples 
3 oranges 
6 tomatoes 
10 pears 

從文本文件?

謝謝

+0

看一看[matplotlib](http://matplotlib.sourceforge.net/index.html)。 – 2010-09-29 12:06:15

回答

6

這裏有一種方法可以爲酒吧分配不同的顏色。它甚至適用於可變數量的酒吧。

import numpy as np 
import pylab 
import matplotlib.cm as cm 

arr = np.genfromtxt('data', dtype=None) 
n = len(arr) 
centers = np.arange(n) 
colors = cm.RdYlBu(np.linspace(0, 1, n)) 
pylab.bar(centers, arr['f0'], color=colors, align='center') 
ax = pylab.gca() 
ax.set_xticks(centers) 
ax.set_xticklabels(arr['f1'], rotation=0) 
pylab.show() 

bar chart

+1

我很肯定你可以做到這一點,而無需處理x定位('sep','width','left','center')。實際上,您可以簡單地將'range(n)'用於'set_xticks()',並使用'bar()'的'align ='center''參數。 – EOL 2010-09-29 12:54:55

+0

@EOL:非常感謝您的提示!編輯... – unutbu 2010-09-29 13:03:39

+1

很高興你發現這條評論有用。這裏有另一種說法:在'genfromtxt()'中設置'dtype = None'更容易:數據類型被正確推斷;您還可以免費獲得超過20個字符的水果名稱的防彈代碼。 :) – EOL 2010-09-29 13:22:26

2

至於其他建議,Matplotlib是你的朋友。類似於

import numpy as np 
import matplotlib.pyplot as plt 

plt.figure() 
indices = np.arange(4) 
width = 0.5 
plt.bar(indices, [10, 3, 6, 10], width=width) 
plt.xticks(indices + width/2, ('Apples', 'Oranges', 'Tomatoes', 'Pears')) 
plt.show() 

將幫助您入門。從文本文件加載數據非常簡單。