Search code examples
pythonmatplotlibbar-chartplt

How to code bar charts with patterns along with colours in Python?


The following code prints a bar chart with four colours:

import matplotlib.pyplot as plt

barlist=plt.bar([1,2,3,4], [1,2,3,4])
barlist[0].set_color('r')
barlist[1].set_color('g')
barlist[2].set_color('y')
plt.show()

enter image description here

The problem is that when printed in black and white, they would look very much alike. Hence my intention would be to produce a graph somewhat like this:

enter image description here

It does not have to look just like the above (forgive the sloppy illustration), but the idea is to have each bar look different when seen in grayscale.

Is there any way this can be implemented in Python?


Solution

  • You can set different patterns inside the bars editing the hatch parameter:

    import matplotlib.pyplot as plt
    
    barlist = plt.bar([1,2,3,4], [1,2,3,4], color=['r','b','y','g'])
    
    barlist[0].set_hatch('//')
    barlist[1].set_hatch('.')
    barlist[2].set_hatch('*')
    barlist[3].set_hatch('o')
    plt.show()
    

    Sample bars figure