Sunday 1 October 2023

How to Add Texture to Bar Charts with Hatch Patterns in Pyplot

What is hatch pattern?

A hatch pattern is a graphical pattern used to fill the interior of a shape (such as a bar in bar chart) with some textual appearance.

 

Example


Following are the most commonly used hatch symbols.

 

a.   '/': Diagonal lines from top-left to bottom-right.

b.   '\': Diagonal lines from bottom-left to top-right.

c.    '-': Horizontal lines.

d.   '|': Vertical lines.

e.   '.': Dots.

f.     'x': Crosshatch

g.   'o' : Circle

 

How to add a hatch pattern to bar in bar chart?

By calling the set_hatch() method on individual bar objects, we can add hatch patterns to the bars in a bar chart.

bars = plt.bar(fruits, liked_by_count, color=colors)
bars[0].set_hatch('/')
bars[1].set_hatch('.')
bars[2].set_hatch('*')
bars[3].set_hatch('o')

Hatch patterns improve the readability of the bar charts.

 

hatch_pattern.py

import matplotlib.pyplot as plt

fruits = ['Apple', 'Banana', 'Orange', 'Grapes']
liked_by_count = [120, 45, 32, 87]
#colors = [(1, 0, 0), 'yellow', 'orange', '#00ff00']

# bars = plt.bar(fruits, liked_by_count, color=colors)
common_background_color = 'lightgray'
bars = plt.bar(fruits, liked_by_count)
for bar in bars:
    bar.set_facecolor(common_background_color)
    
bars[0].set_hatch('/')
bars[1].set_hatch('.')
bars[2].set_hatch('*')
bars[3].set_hatch('o')

plt.xlabel('Fruits')
plt.ylabel('Liked by people')

plt.title('Bar Chart Example')
plt.show()

Output






Previous                                                    Next                                                    Home

No comments:

Post a Comment