Search code examples
pythonnumpymatplotlibpolar-coordinates

How to create a circular frequency histogram


Dear members of stackoverflow,

I want to create a circular frequency histogram (rose diagram) using the the frequencies for each bin listed as a single column in a text file. How could I do this using matplotlib.pyplot and numpy in python3?

I did an initial attempt with a code I found on the internet, but when I get the rose diagram the bins are overlapped when they should be beside each other. Other detail: the radius of the circle for each bin should be the frequency, but this also changes and does not match my frequencies. I want my bins to go from 0 to 360 degrees with width of 10 degrees; example: 0-10, 10-20 etc.

This is a sample of the txt file with the frequencies(frequencies.txt):

0
0
0
0
0
2
0
1
1
0
1
0
0
1
2
29
108
262
290
184
81
25
7
2
3
1
1
0
0
0
0
0
0
0
0
0

enter image description here


Solution

  • You could create a polar bar plot. The angles need to be converted from degrees to radians.

    frequencies = np.loadtxt('filename.txt') would read the values from file (docs).

    import numpy as np
    import matplotlib.pyplot as plt
    
    frequencies = [0, 0, 0, 0, 0, 2, 0, 1, 1, 0, 1, 0, 0, 1, 2, 29, 108, 262, 290,
                   184, 81, 25, 7, 2, 3, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    
    fig = plt.figure()
    ax = plt.axes(polar=True)
    
    theta = np.radians(np.arange(0, 360, 10))
    width = np.radians(10)
    ax.bar(theta, frequencies, width=width,
           facecolor='lightblue', edgecolor='red', alpha=0.5, align='edge')
    ax.set_xticks(theta)
    plt.show()
    

    polar bar plot