2017-02-03 7 views
2

私は、コードを1から100までの100個の乱数を生成:乱数のヒストグラムを生成するにはどうすればよいですか?

def histogram(): 
    for x in range(100): 
     x = random.randint(1, 100) 
     print(x) 

を今私は、ヒストグラムにこの情報を表現しようとしています、私はPLTとしてmatplotlib.pyplotインポートし、これを構築しようとしたが、私はあるように見えます問題に遭遇する。

私が試した:

def histogram(): 
    for x in range(100): 
     x = random.randint(1, 100) 
     return x  
    histogram_plot = histogram() 
    plt.hist(histogram_plot) 
    plt.show() 

を私も試してみました:

def histogram(): 
    for x in range(100): 
     x = random.randint(1, 100) 
     print(x) 
     plt.hist(x) 
     plt.show() 

は私が間違って何をしているのですか?ここで

+0

だから、あなたは何を得ていますか? – vovaminiof

+0

無条件の 'return'をループ内に置くことは、ループの1回の反復の後に関数が返ることを意味します。あなたは本当にそれを望んでいない! –

答えて

3

は、あなたが持っている問題は、あなたのhistogram機能であるあなたのコード

>>> import matplotlib.pyplot as plt 
>>> import random 
>>> data = [random.randint(1, 100) for _ in range(100)] 
>>> plt.hist(data) 
(array([ 15., 13., 9., 9., 11., 9., 9., 11., 6., 8.]), 
array([ 1. , 10.9, 20.8, 30.7, 40.6, 50.5, 60.4, 70.3, 80.2, 90.1, 100. ]), 
<a list of 10 Patch objects>) 
>>> plt.show() 

enter image description here

に似ている小規模作業例です。ランダム値のlistを構築するのではなく、変数xをランダムにintに再割り当てします。

1

最初の関数では、ループ内にreturnがあるため、インタプリタがプロットコードに到達しないため、結果はプロットされません。 2番目の例では、反復処理を行い、毎回1つのインスタンスをプロットします。

は、単にランダムな番号のリストを作成し、それらをプロットします

def histogram(): 
    xs = [random.randint(1, 100) for _ in range(100)] 
    print(x) 
    plt.hist(xs) 
    plt.show() 
関連する問題