Search code examples
pythonnumpymatplotlibbar-chartyaxis

send pyplot grid color to background and percentage values starting from 20 instead of 0


I am using pyplot to make a bar chart. I have one line of code where I set a grid for the plot as follow:

plt.grid(color='#95a5a6', linestyle='--', linewidth=2, axis='y', alpha=1)

I need to send the grid into the background instead of the back ground.

Also, the y axis values start from 0%. I want to start the values from 20% instead.

Here is the complete code:

plt.bar(r1, dao, color='blue', width=barWidth, edgecolor='white', label='DAO')
plt.bar(r2, pie_gdp, color='orange', width=barWidth, edgecolor='white', label='PIE- GDP')
plt.bar(r3, pie_sdp, color='gray', width=barWidth, edgecolor='white', label='PIE-SDP')
plt.grid(color='#95a5a6', linestyle='--', linewidth=2, axis='y', alpha=1)

plt.xticks([r + barWidth for r in range(len(dao))], ['DNN-Sigmoid', 'CNN-Sigmoid', 'DNN-ReLU', 'CNN-ReLU'])
plt.gca().set_yticklabels(['{:.0f}%'.format(x*1) for x in plt.gca().get_yticks()])
plt.legend(loc='lower center', bbox_to_anchor=(0.5, -0.20), ncol=3)

plt.show()

dao, pie_gdp, and pie_sdp are np.arrays containing the data I am plotting


Solution

  • Use ax.set_axisbelow(True) to have the grid lines behind the elements on the plot. plt.ylim() (or ax.set_ylim()) can change the data limits. The PercentFormatter formats the tick labels as percentages.

    import matplotlib.pyplot as plt
    from matplotlib.ticker import PercentFormatter
    import numpy as np
    
    barWidth = 0.8 / 3
    r1 = np.arange(4)
    r2 = r1 + barWidth
    r3 = r2 + barWidth
    dao = np.random.uniform(20, 100, 4)
    pie_gdp = np.random.uniform(20, 100, 4)
    pie_sdp = np.random.uniform(20, 100, 4)
    
    plt.bar(r1, dao, color='blue', width=barWidth, edgecolor='white', label='DAO')
    plt.bar(r2, pie_gdp, color='orange', width=barWidth, edgecolor='white', label='PIE- GDP')
    plt.bar(r3, pie_sdp, color='gray', width=barWidth, edgecolor='white', label='PIE-SDP')
    plt.grid(color='#95a5a6', linestyle='--', linewidth=2, axis='y', alpha=1)
    ax = plt.gca()
    ax.set_axisbelow(True)  # grid lines behind other elements
    
    plt.xticks(r1 + barwidth, ['DNN-Sigmoid', 'CNN-Sigmoid', 'DNN-ReLU', 'CNN-ReLU'])
    plt.ylim(20, None)  # start from 20
    ax.yaxis.set_major_formatter(PercentFormatter(100))
    for spine in ['top', 'right']:
        ax.spines[spine].set_visible(False)  # hide part of the box
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1), ncol=3)
    
    plt.tight_layout()  # fit subplot and texts nicely into the figure
    plt.show()
    

    bar plots