How to Set Colors for Bar Plot in Matplotlib – Python
In this tutorial, we will see how to set colors for Bar Plot in Python using Matplotlib. It provides a wide range of plotting functions and tools for creating figures, plots, histograms, power spectra, bar charts, error charts, scatterplots, etc.
Set bar colors for the bar chart in Matplotlib
To set the color for the bars in Matplotlib, we can use color parameters with the color name like ‘red’, ‘green’, ‘blue’ or the hex value like ‘#8b0202’, ‘#F4BB44’, ‘#FFED85’, etc.
We can provide a single color value, or a list of colors to the color parameter.
ax.bar(fruit, price, color='red') #Color name as parameter ax.bar(fruit, price, color=['red', 'green']) #Multiple color name as parameter ax.bar(fruit, price, color='#8b0202') #HEX value as parameter ax.bar(fruit, price, color=[#8b0202', '#F4BB44']) #Multiple HEX value as parameter
Single Color and Multi-Color bar chart
Here in this example, I took a sample data frame with fruit and its prices. We will plot the data frame in a 2,1 subplot to show one subplot with all bars single-colored in the second subplot. I used a multicolor bar chart in which each bar has a different color.
import matplotlib.pyplot as plt #Sample dataframe fruit = ['Apple', 'Mango', 'Banana', 'Orange'] price = [149, 110, 60, 45] # Create a figure and 2 subplots fig, ax = plt.subplots(2,1) # Plot a bar chart on the first subplot ax[0].bar(fruit, price, color='orange') ax[0].set_xlabel('Fruits') ax[0].set_ylabel('Price') ax[0].set_title('Single Color') # Plot a bar chart on the second subplot ax[1].bar(fruit, price, color=['#8b0202', '#F4BB44', '#FFED85', '#FFA500']) ax[1].set_xlabel('Fruits') ax[1].set_ylabel('Price') ax[1].set_title('Multi Color') # Show the plot plt.tight_layout() plt.show()
Leave a Reply