#191 Custom axis on matplotlib chart

This page describes several customisations you can apply on the axis of your matplotlib chart. These examples are applied on the X axis but can naturally be imitated for the Y axis!

  • The title of the axis can be customised through the xlabel function (ylabel respectively). The argument names speak by themselves so I hope the code provided below is self explanatory.

    
    # Basic plot
    import numpy as np
    import matplotlib.pyplot as plt
    height = [3, 12, 5, 18, 45]
    bars = ('A', 'B', 'C', 'D', 'E')
    y_pos = np.arange(len(bars))
    plt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
    
    # Custom Axis title
    plt.xlabel('title of the xlabel', fontweight='bold', color = 'orange', fontsize='17', horizontalalignment='center')
    
    
  • Use the tick_params function to custom or to remove the ticks.

    
    # Basic plot
    import numpy as np
    import matplotlib.pyplot as plt
    height = [3, 12, 5, 18, 45]
    bars = ('A', 'B', 'C', 'D', 'E')
    y_pos = np.arange(len(bars))
    plt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
    
    # Custom ticks
    plt.tick_params(axis='x', colors='red', direction='out', length=13, width=3)
    
    # You can remove them:
    plt.tick_params(bottom='off')
    

  • You can custom the labels with the xticks function. And remove them with the tick_params function.

    
    # Basic plot
    import numpy as np
    import matplotlib.pyplot as plt
    height = [3, 12, 5, 18, 45]
    bars = ('A', 'B', 'C', 'D', 'E')
    y_pos = np.arange(len(bars))
    plt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
    
    # use the plt.xticks function to custom labels
    plt.xticks(y_pos, bars, color='orange', rotation=45, fontweight='bold', fontsize='17', horizontalalignment='right')
    
    # remove labels
    plt.tick_params(labelbottom='off')
    


  • Last but not least, set the limit of your axis with the …. xlim function !

    
    # Basic plot
    import numpy as np
    import matplotlib.pyplot as plt
    height = [3, 12, 5, 18, 45]
    bars = ('A', 'B', 'C', 'D', 'E')
    y_pos = np.arange(len(bars))
    plt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
    
    # Set the limit
    plt.xlim(0,20)
    

Leave a Reply

Your email address will not be published.