pythonmatplotlibplotradar-chartspider-chart

Matplotlib: Radar Chart - axis labels


I am trying to plot a radar chart with 15 labels on the xaxis. The data is plotted correctly, but I am unable to define the axis labels properly. The plot I get is as follows: acheived

As you can see, the number of axis ticks generated is less than the number of bars generated. How can I generate equal number of ticks (and corresponding tick labels) to clearly distinguish each bar? What I want is something similar to the image shown below: required

The code that I am currently using is as follows:

fig = figure(figsize=(8,8))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
 sample = np.random.uniform(low=0.5, high=13.3, size=(15,))
 N = len(sample) 
items=['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15'] 
theta = np.arange(0, 2*np.pi, 2*np.pi/N) 
bars = ax.bar(theta, sample, width=0.4) 
ax.set_xticklabels(items)
 ax.yaxis.grid(True)
 show()

What am I missing? Thanks in advance!


Solution

  • Using ax.set_xticklabels sets the text of the labels.

    What you really want is to set the positions of the labels. In this case the positions are just the items of the theta array

    ax.set_xticks(theta)
    

    Once those ticks are set, one can of course change their labels, which in this case are just the first N numbers starting at 1,

    ax.set_xticklabels(range(1, len(theta)+1))
    

    A complete example:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure(figsize=(8,8))
    ax = fig.add_subplot(111,polar=True)
    
    sample = np.random.uniform(low=0.5, high=13.3, size=(15,))
    N = len(sample) 
    
    theta = np.arange(0, 2*np.pi, 2*np.pi/N) 
    bars = ax.bar(theta, sample, width=0.4)
    
    ax.set_xticks(theta)
    ax.set_xticklabels(range(1, len(theta)+1))
    ax.yaxis.grid(True)
    plt.show()
    

    enter image description here

    Note that in matplotlib versions prior to 2.x, you need to center the bars to obtain the result from above

    bars = ax.bar(theta, sample, width=0.4, align="center")