Prettier default plot colors in matplotlib
In this tutorial, we will make beautiful plots with different colors with matplotlib Python library. While working with plots in matplotlib, we often see that default blue shade everywhere. But, one of the best features of matplotlib is, it is very customizable.
Working with colors
Although there are some predefined colors in matplotlib, it is also possible to give other colors in the form of hex codes. Let us use a custom color palette and define hex strings as variables.
HEX_Green = '#47DBCD' HEX_Purple = '#9D2EC5' HEX_Pink = '#F3A0F2' HEX_Blue = '#2CBDFE' HEX_Violet = '#661D98' HEX_Amber = '#F5B14C'
Now, these variables are put into a list and passed to Matplotlib’s color ‘cycler’.
import matplotlib.pyplot as plt color_list = [HEX_Green, HEX_Purple, HEX_Pink, HEX_Blue, HEX_Violet, HEX_Amber] plt.rcParams['axes.prop_cycle'] = plt.cycler(color=color_list)
- After executing the above lines of code, the default color of all plots using matplotlib will be changed to ‘HEX_Green’.
- If there is a multi-category plot, then the colors will be iterated in order through the list.
import matplotlib.pyplot as plt import numpy as np x = [2,4,6,8,10] y = [5,5,5,5,5] plt.plot(x, y, label = "line 1") plt.plot(x, np.log(x), label = "curve 1") plt.plot(y, x, label = "line 2") plt.plot(x, np.sin(x), label = "curve 2") plt.legend() plt.show()
- If you want gradients using lists of hex colors, it will be hard to type all the colors. So, you can refer colormap or generate using codedesigner.
We can change the inner and outer colors of plots by using some methods but not by default.
- ax.set_facecolor(‘color’) method is used to change inner color.
- plt.figure(facecolor=’color’) method is used to change outer color.
Leave a Reply