Sunday, 24 September 2023

Styling Your Text with the fontdict Argument in Matplotlib

Using 'fontdict' parameter, we can seggregate all the font specific parameters in a dictionary and customize the appearance of text elements in the plot. In general, 'fontdict' parameter is used with various functions like plt.title(), plt.xlabel(), plt.ylabel(), plt.legend(), plt.text(), plt.figtext() and others.

 

'fontdict' dictionary contain folowing keys.

a.   family: Specifies the font family, Ex: "serif" or "sans-serif".

b.   size: Specifies the font size, in points.

c.    weight: Specifies rhe font weight, such as "normal" or "bold".

d.   color: Specifies the font color, such as "blue" or "#00ff00".

e.   style: Specifies the font style, such as "normal" or "italic".

f.     variant: Specifies the font variant, such as "normal" or "small-caps".

g.   stretch: Specifies the font stretch, such as "normal" or "expanded".

 

Example

my_title_font = {
    'family': 'serif',
    'size': 20,
    'weight': 'bold',
    'color': 'blue',
    'style': 'italic',
}

plt.title('font dictionary example', fontdict=my_title_font)

 

font_dictionary.py

import matplotlib.pyplot as plt

# Sample data
x1 = [5, 10, 15, 20, 25]
y1 = [20, 40, 60, 80, 100]

plt.plot(x1, y1, 'rs--', label='4x', markersize=5)

# To display the legend on the plot
plt.legend()

my_title_font = {
    'family': 'serif',
    'size': 20,
    'weight': 'bold',
    'color': 'blue',
    'style': 'italic',
    'stretch' : 'expanded',
    'variant' : 'small-caps'
}

plt.title('font dictionary example', fontdict=my_title_font)

plt.show()

 

Output


 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment