How to change font color in matplotlib – Python
In this tutorial, we will be learning how to change the font color in matplotlib in Python. In this, we will be using the ‘Matplotlib’ library and more specifically the ‘Pyplot’ module for drawing the graph and for adding text we will be using ‘Text’ in matplotlib plots.
It is very common that we need to change the color of the text to make our document more attractive. Therefore we need to know how to change the font color while using the matplotlib for creating the graphs to make them more detailed and focusable.
About Matplotlib Library
Matplotlib is a Python library, that produces high-quality 2D figures in a variety of publishable formats. It is a platform-independent library that tries to make work easier and produces results in fewer lines of code. We can generate plots, histograms, bar charts, error charts, etc using matplotlib.
Pyplot module provides an interface which is some more similar to MATLAB and some functions using which we can create figures, create plotting area in the figure, plot some lines or text in the plotting area, etc.
Text is used for inserting formatted text in the plots. So that what is appearing on screen should be present in the document.
To learn more about the matplotlib and pyplot module you can refer to its documentation.
Change font color in matplotlib – Python
Firstly, we need to install the required library:
$ python -m pip install -U matplotlib
Now, comes the source code, I would suggest you go through the code thoroughly it is pretty easy to understand afterward I’ll be explaining you the necessary details.
# Importing the required module import matplotlib.pyplot as plt # Setting the axis of pyplot plt.axis([0,5,0,5]) # Creating a String Object string = "This is a sample string" # Adding the text with red color plt.text(1, 4, string, fontsize=15, color="red") # Adding the text with green color plt.text(2, 3, string, fontsize=15, color="green") # Adding the text with blue color plt.text(3, 2, string, fontsize=15, color="Blue") # Function for showing plot plt.show()
First of all I had imported the required module from matplotlib library, then I had set axis as a 5X5 grid, then I had created a string object for placing into the text, then I had inserted three text plots in the graph each of different color and finally I had used function for displaying the plot.
So in this way, we can change the font color in matplotlib in python. I hope this tutorial was helpful to you, Thank you ‘Keep Learning Keep Coding’.