Search code examples
pythonpandasmatplotlibhistogramprobability

Plot a histogram in matplotlib (pandas) X and Y axes specifications


For the rolling of a six sided dice, I need to randomly simulate the event 50 times and plot a histogram of results for each number on the dice while using number of bins=6

I tried the following:

import random
 
test_data = [0, 0, 0, 0, 0, 0] 
n = 50 

for i in range(n):
  result = random.randint(1, 6)
  test_data[result - 1] = test_data[result - 1] + 1

plt.hist(test_data,bins=6)

Is there a way to plot the numbers of the dice on the x axis and results for each number on the dice on the y axis?


Solution

  • For what you are trying to do, I believe it is more correct to use a barchart, as the different possible results (X axis) are not frequencies. For your purpose, then, I think it is better to use a dictionary doing something like this:

    import random
    from matplotlib import pyplot as plt
     
    test_data = {"1":0, "2":0, "3":0, "4":0, "5":0, "6":0}
    n = 50 
    
    for i in range(n):
      result = random.randint(1, 6)
      test_data[str(result)] += 1
    
    plt.bar(test_data.keys(), test_data.values())
    plt.show()
    

    That should do the trick. Hope it helped!