2016-07-31 48 views
0

我想用matplotlib在Python中自動化一個頻率圖,以便計算出現次數,而不是必須在Excel中手動繪圖。但是,我無法像在Excel中那樣製作類似於可能的圖表。這是Matplotlib可能嗎?頻率圖與matplotlib

在Excel:

enter image description here

代碼:

#!/usr/bin/python 

import numpy as np 
import matplotlib.pyplot as plt 
from numpy import * 
import os 
import sys 
import csv 
from random import randint 

x = [6,0,0,26,0,0,0,0,5,0,7,0,12,12,0,0,0,3,0,5,5,0,10,4,3,5,1,0,2,0,0,1,0,8,0,3,7,1,0,0,0,1,1,0,0,0,0,0,7,16,0,0,0,5] 


plt.hist(x) 
plt.title("Frequency diagram") 
plt.xlabel("Value") 
plt.ylabel("Frequency") 
plt.show() 

結果(可讀性不相爲Excel一樣好,我怎麼可以把它作爲類似Excel的圖表):

enter image description here

回答

2
import numpy as np 
import matplotlib.pyplot as plt 

def make_hist(ax, x, bins=None, binlabels=None, width=0.85, extra_x=1, extra_y=4, 
       text_offset=0.3, title=r"Frequency diagram", 
       xlabel="Values", ylabel="Frequency"): 
    if bins is None: 
     xmax = max(x)+extra_x 
     bins = range(xmax+1) 
    if binlabels is None: 
     if np.issubdtype(np.asarray(x).dtype, np.integer): 
      binlabels = [str(bins[i]) if bins[i+1]-bins[i] == 1 else 
         '{}-{}'.format(bins[i], bins[i+1]-1) 
         for i in range(len(bins)-1)] 
     else: 
      binlabels = [str(bins[i]) if bins[i+1]-bins[i] == 1 else 
         '{}-{}'.format(*bins[i:i+2]) 
         for i in range(len(bins)-1)] 
     if bins[-1] == np.inf: 
      binlabels[-1] = '{}+'.format(bins[-2]) 
    n, bins = np.histogram(x, bins=bins) 
    patches = ax.bar(range(len(n)), n, align='center', width=width) 
    ymax = max(n)+extra_y 

    ax.set_xticks(range(len(binlabels))) 
    ax.set_xticklabels(binlabels) 

    ax.set_title(title) 
    ax.set_xlabel(xlabel) 
    ax.set_ylabel(ylabel) 
    ax.set_ylim(0, ymax) 
    ax.grid(True, axis='y') 
    # http://stackoverflow.com/a/28720127/190597 (peeol) 
    ax.spines['top'].set_visible(False) 
    ax.spines['right'].set_visible(False) 
    ax.spines['bottom'].set_visible(False) 
    ax.spines['left'].set_visible(False) 
    # http://stackoverflow.com/a/11417222/190597 (gcalmettes) 
    ax.xaxis.set_ticks_position('none') 
    ax.yaxis.set_ticks_position('none') 
    autolabel(patches, text_offset) 

def autolabel(rects, shift=0.3): 
    """ 
    http://matplotlib.org/1.2.1/examples/pylab_examples/barchart_demo.html 
    """ 
    # attach some text labels 
    for rect in rects: 
     height = rect.get_height() 
     if height > 0: 
      plt.text(rect.get_x()+rect.get_width()/2., height+shift, '%d'%int(height), 
        ha='center', va='bottom') 

x = [6,0,0,26,0,0,0,0,5,0,7,0,12,12,0,0,0,3,0,5,5,0,10,4,3,5,1,0,2,0,0,1,0,8,0, 
    3,7,1,0,0,0,1,1,0,0,0,0,0,7,16,0,0,0,5,41] 
fig, ax = plt.subplots(figsize=(14,5)) 
# make_hist(ax, x) 
# make_hist(ax, [1,1,1,0,0,0], extra_y=1, text_offset=0.1) 
make_hist(ax, x, bins=list(range(10))+list(range(10,41,5))+[np.inf], extra_y=6) 
plt.show() 

enter image description here

make_hist試圖確定是否所有的值在x是整數。如果是這樣,它使用基於整數的箱標籤。例如,箱標籤10-14代表範圍[10, 14](含)。

另一方面,如果x包含浮標,則make_hist將使用半打開的基於浮標的紙槽標籤。例如,10-15將代表半開範圍[10, 15)

+0

哇!謝謝,那很多代碼。但是,當我將列表的值更改爲例如'x = [1,1,1,0,0,0]'時,該圖表顯示不正確?它是動態的嗎?由於這些值會有所不同。 – user3580316

+0

我在「箱子」的定義中一個接一個。也許再試一次。 – unutbu

+0

謝謝。但是,我想知道爲什麼它不顯示35以上的任何值?是否有可能例如將最後一個柱作爲40+的值,其中40以上的值是其中的一部分?由於'x'值可能會改變並且不是靜態的。非常感謝你的幫助。 – user3580316