Matplotlib Styles for Scientific Plotting | by Rizky Maulana N | Towards Data Science

There are at least two inspirations in writing this story. The first inspiration is coming from my participation in Summer School on Galaxies and Cosmology (SSGC 2020). It has three parts: Public Lecture, Lectures, and Workshops. One of the Workshops analyzed the weak gravitational lensing using Oguri et al. (2012) as the primary reference. Oguri-san gave the participants his code to analyze the lensing, including the Maptlotlib parameter settings. I won’t talk about the gravitational lensing, but how to generate a professional plot using Matplotlib, as shown in Oguri-san paper.
The other one comes from when I was reading the General Instructions to submit an article in Monthly Notices of the Royal Astronomical Society (MNRAS), one of the world’s leading primary research journals in astronomy and astrophysics. One of the parts in the instructions is how to embed figures in MNRAS. The authors are advised to ensure the color used in their figures are color-blind friendly. Here, I quote the instruction.
Where possible, please ensure that your figures are color-blind friendly. The use of red and green in the same figure is particularly problematic for some readers (General Instructions from MNRAS)
I was surprised by the instruction. I did not realize that we need to provide color-blind friendly in my figures/plots because I have no problem with color. After understanding it, I suggest you (all of the readers) perform color-blind friendly in your figures/plots. I will explain more about color blindness in the next part.
This story will guide you on how to:
Customize Matplotlib parameters, using plotting style and rcParamsChoose color-blind friendly
Customize Matplotlib parameters, using plotting style and rcParams
Choose color-blind friendly
This story is significant for you who boost your data visualization skills because I will share how to generate professional plots based on the main goals mentioned before. So, let’s start it.
Matplotlib provides users the style package to customize plotting style. If you did not change the style, you would get a default style, as shown in Figure 1.
By default, the background color is white, and the first color for the plot is blue. You can change it using style syntax, as shown in the following code.
import matplotlib as pltplt.style.use('fivethirtyeight') # fivethirtyeight is name of style
After applying it, you will get the result, as shown in Figure 2.
It’s pretty cool, I think. How about the other styles? How many styles Matplotlib provides? You can check it using this code.
print(plt.style.available)
You will get all available styles provided by Matplotlib, as shown in Figure 3.
Can you count it? :D. There are 26 different styles you can use in Matplotlib. I have generated plots using all of the plotting styles, but I will show you just four of them, as shown in Figure 4.
I suggest you check all the plotting styles in Matplotlib, choose your favorite styles, and make it your default style. If you want to reset the plotting style, you can use this code.
plt.style.use('default')
Back to this story’s inspiration, I will show the figure example used by Oguri-san in his paper, as shown in Figure 5.
Customize Matplotlib parameters using rcParamsThere are seven settings that I will share with you using rcParams in Matplotlib. They are using LaTeX font, customizing font size, adjusting legend text length, customizing axes line width, changing x-axis and y-axis tick direction, and the last is adjusting the major and minor size for the x-axis and y-axis tick. Let’s discuss it one by one.
Use LaTeX font
As you can see in Figure 5, Oguri-san uses LaTeX for his plots. For many people, they need some special symbol which is hidden by Matplotlib. In Matplotlib, the LaTeX font is deactivated by default. To activate it, you can use this code.
plt.rcParams['text.usetex'] = True
You can visit my other story that explains more detail about using LaTeX font in Matplotlib by clicking this link.
towardsdatascience.com
If I apply the LaTeX font in Figure 4, I will get a different result, as shown in Figure 6. You can compare the font used in the title, axis, tick, and the text in Figure 4 and Figure 6.
Adjust font size
You can adjust the font size using this code.
plt.rcParams[‘font.size’] = 15
Matplotlib gives you 10, given in pts, as the default font size. In the code above, I change it from 10 to 18 pts. Parameter font.size control all text size, including title, x-axis and y-axis label, the x-axis and y-axis tick, legend, text, and annotation. You can change the font size for each element (for example, title) using another code. For example, you want to adjust all of the text sizes to 18, but the legend will be 20. You can adjust it with this code.
plt.rcParams[‘font.size’] = 15plt.rcParams['legend.fontsize'] = 18
You will get different representations of the font size if you declare a different figure size, even if you have the same font size. This condition is shown in Figure 7.
The difference between the two plots in Figure 7 is from the calibration of font size in pts.
Change x-axis and y-axis tick direction
If you see the Oguri-san plot (Figure 5) in more detail, you will see that the tick direction in the x-axis and y-axis is in the axes, not outside of the axis. You can compare Figure 5 and Figure 7, especially in the tick direction.
By default, the direction of the tick (x-axis and y-axis) is in the axes. You can change it by typing the following code.
plt.rcParams['xtick.direction'] = 'out'plt.rcParams['ytick.direction'] = 'out'
There are three options you can use: in, out, and inout. You can see the different results of them in Figure 8.
Adjust major and minor tick size
In Figure 8, I think you can not see the difference between the three plots because the tick’s size is too small. How to make it bigger? You can change it using this code for the x-axis and y-axis.
plt.rcParams['xtick.major.size'] = 5.0plt.rcParams['xtick.minor.size'] = 3.0plt.rcParams['ytick.major.size'] = 5.0plt.rcParams['ytick.minor.size'] = 3.0
Matplotlib gives you xtick and ytick major size of 3.5 and for minor tick is 2.0. To show the minor tick, you can use this code.
from matplotlib.ticker import MultipleLocatorax.xaxis.set_minor_locator(MultipleLocator(.5))ax.yaxis.set_minor_locator(MultipleLocator(.005))
Of course, you need to define ax using
fig, ax = plt.subplots(figsize=(xsize, ysize))
or
ax = plt.gca()
Here is the code to figure with configuring the minor tick
If you run the code, you will get a figure, as shown in Figure 9.
Adjust line width
In this part, I will share with you how to adjust the line width of the axes. You can use this code to adjust it.
plt.rcParams['axes.linewidth'] = 3.0
By default, the line width is set to 0.8, given in pts. I set it in 3.0 to feel the difference between the default setting and the updated version. If you add the code above in Figure 9, it will give the result shown in Figure 10.
As you see in Figure 10, the now minor tick is not visible because the minor tick size is smaller than the line width.
Adjust handle length
In the last part, I will demonstrate how to adjust the handle length and the distance between the text legend and its symbol. I think you will know more if you run the following code and analyze the result, as shown in Figure 11.
plt.rcParams['legend.handlelength'] = 5.0
You can see the difference in the legend box. I set it to 5.0 so that you can see the difference clearly.
Here is the full style to create scientific plots for your data visualization
fsize = 15tsize = 18tdir = 'in'major = 5.0minor = 3.0lwidth = 0.8lhandle = 2.0plt.style.use('default')plt.rcParams['text.usetex'] = Trueplt.rcParams['font.size'] = fsizeplt.rcParams['legend.fontsize'] = tsizeplt.rcParams['xtick.direction'] = tdirplt.rcParams['ytick.direction'] = tdirplt.rcParams['xtick.major.size'] = majorplt.rcParams['xtick.minor.size'] = minorplt.rcParams['ytick.major.size'] = 5.0plt.rcParams['ytick.minor.size'] = 3.0plt.rcParams['axes.linewidth'] = lwidthplt.rcParams['legend.handlelength'] = lhandle
Color blindness (or color blindness — or more specific color vision deficiency (CVD)) is well known but hard to imagine if you are not suffering. Before I know the data from https://www.color-blindness.com/, I did not realize that people who have color blindness is not small, approximately every 1 in 12 men (8%) and 1 in 200 women (0.5%). So, if you want to generate figures/plots, please ensure it is color-blind friendly.
There are four types of color blindness, they are Protan Color Blindness, Deutan Color Blindness, Tritan Color Blindness / Tritanomaly, and Monochromacy and Achromatopsia. Detail information for each type can be accessed here.
One of the safest solutions you can use to deal with color blind is to avoid using red and green together. For simply, you can use the service from Gregor Aisch in https://gka.github.io/palettes. You can generate many palettes, which is color-blind friendly. To use it, first, you need to choose what palettes type you want to create. There are two options, sequential and diverging, as shown in Figure 12.
After that, in the same section (section number 1), you need to declare how many colors you want to generate. In this story, I will choose diverging colors, with the number of colors is 5.
In section 2, you can fill it with several colors you want in the Hex color code. If you just know the colors you want in RGB, you can transform it using this link. I choose these colors for the left panel.
#0051a2, #10542c, #ffd44f
and these colors for the right panel.
lightyellow, #ff005e, #93003a
In section 3, check correct lightness and bezier interpolation. If your choice colors are color-blind friendly, you will get the information “The palette is color-blind safe” in the right panel of section 3, as shown in Figure 13.
Then, scroll down in section 4, “Export the color codes in various formats.” You can pick the color code to generate from the colors in section 3. Here is the color code I got.
['#0051a2', '#97964a', '#ffd44f', '#f4777f', '#93003a']
How to apply it? Just declare it as your color in your plots. Here is the example of my plot, shown in Figure 14.
It’s still pretty and, of course, color-blind friendly. You can vary the colors you want to generate. Please ensure that you get the notification that says The palette is color-blind safe in section 2.
You can see the example of my chosen colors that is not color-blind friendly.
If you got a notification like that, please change the colors to help the people who have color blindness.
If you want to apply the colorblind-safe palettes to your colormaps, you need to build your own colormaps. You can learn how to create your own colormaps using my other story in the following link.
towardsdatascience.com
To boost your skills in data visualization using Matplotlib, you need to make a plotting template. It can be built by choosing your right plotting style, adjusting some basic parameters using rcParams, and choosing the color-blind friendly palettes. I hope this story can help you create scientific and professional plots considering some information I mentioned before.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
medium.com
That’s all. Thanks for reading this story. Comment and share if you like it. I also recommend you follow my account to get a notification when I post my new story.
[1] Oguri, M et al., (2012) MNRAS Volume 420, Issue 4, March 2012, Pages 3213–3239, https://doi.org/10.1111/j.1365-2966.2011.20248.x
[2] MNRAS, General Instruction for Submission in MNRAS https://academic.oup.com/mnras/pages/General_Instructions
[3] Color Blindness https://www.color-blindness.com/
[4] Color-blind friendly palettes https://gka.github.io/palettes
[5] Color code transformation https://html-color-codes.info/convert-color-format/