#7 Custom barplot layout

Here are 3 examples of customisation you could probably need for your barplots.

  • Labels

    
    # libraries
    import numpy as np
    import matplotlib.pyplot as plt
    
    # Choose the height of the bars
    height = [3, 12, 5, 18, 45]
    
    # Choose the names of the bars
    bars = ('group1', 'group2', 'group3', 'group4', 'group5')
    y_pos = np.arange(len(bars))
    
    # Create bars
    plt.bar(y_pos, height)
    
    # Create names on the x-axis
    plt.xticks(y_pos, bars, color='orange')
    plt.yticks(color='orange')
    
    # Show graphic
    plt.show()
    
    
  • This example shows how to custom the group labels, through the xlabel function.

    
    # libraries
    import numpy as np
    import matplotlib.pyplot as plt
    
    # Create data
    height = [3, 12, 5, 18, 45]
    bars = ('A','B','C','D','E')
    
    # Create bars
    plt.bar(y_pos, height)
    
    # Create names on the x-axis
    plt.xticks(y_pos, bars)
    plt.xlabel('category', fontweight='bold', color = 'orange', fontsize='18')
    
    # Show graphic
    plt.show()
    
    
  • A common problem in barplot is to find a way to display the group labels properly. If you them to be readable, you probably need to rotate them and increase the margin size:

    
    # libraries
    import numpy as np
    import matplotlib.pyplot as plt
    
    # Create data
    height = [3, 12, 5, 18, 45]
    bars = ("very long group name 1","very long group name 2","very long group name 3","very long group name 4","very long group name 5")
    
    # Create bars
    plt.bar(y_pos, height)
    
    # Rotation of the bars names
    plt.xticks(y_pos, bars, rotation=90)
    
    # Custom the subplot layout
    plt.subplots_adjust(bottom=0.4, top=0.99)
    
    # Show graphic
    plt.show()
    
    

Leave a Reply

Your email address will not be published.