Matplotlib data visualization

Task04
This study refers to Datawhale open source learning: https://github.com/datawhalechina/fantastic-matplotlib
The content is generally derived from the original text and adjusted in combination with their own learning ideas.
Personal summary: first, Matplotlib mainly has two ways to create text: pyplot API and objective oriented API. 2. Text setting can also be divided into direct setting and using instantiation method.

4. Text legend

Matplotlib has extensive text support. There are two ways to create text: pyplot API and object oriented API.

pyplot APIOO APIdescription
texttextstay Axes Add text anywhere in the.
titleset_titlestay Axes Add title
figtexttextstay Figure Add text anywhere
suptitlesuptitlestay Figure Add title
xlabelset_xlabelstay Axes Add label to x-axis
ylabelset_ylabelstay Axes Add label to y-axis

4.1. Text on figure and Axes

4.1.1. title and set_title

pyplot API:matplotlib.pyplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
OO API:Axes.set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
This command is used to set the title of axes.
parameter
label: str, this parameter is the text to be added
Fontdict: dict. This parameter controls the appearance of title text. The default fontdict is as follows:
loc:str, {'center', 'left', 'right'} defaults to center
pad:float. This parameter refers to the distance from the title to the top of the chart. The default value is 6.
y:float, which is the vertical position of the axes where the title is located. The default value is 1, that is, the title is at the top of axes.
kwargs: this parameter refers to the attributes of some strange text that can be set.
Return value
Returns the text as the created title instance.

4.1.2. figtext and text

pyplot API:

  • matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
  • matplotlib.pyplot.figtext(x, y, s, fontdict=None, **kwargs)
    (where text writes text on the subgraph and figtext writes text on fig)

OO API:text(self, x, y, s, fontdict=None,**kwargs)
parameter
x. Y: float, this parameter refers to the position where the text is placed in figure. The general value is in the range of [0,1]. Use the transform keyword to change the coordinate system.
s:str, this parameter refers to the text
fontdict:dict, which is an optional parameter and a dictionary that overrides the default text attribute. If fontdict is None, the default value is determined by rcParams.
Return value
Returns the text as an instance of the created text.

4.1.3. suptitle

pyplot API: matplotlib.pyplot.suptitle(t, **kwargs)
OO API:suptitle(self, t, **kwargs)
parameter
t: str, text of the title
x: float, the default value is 0.5. This parameter refers to the X coordinate of the text in the figure coordinate system
y: float, the default value is 0.95. This parameter refers to the Y coordinate of the text in the figure coordinate system
Horizontal alignment, ha: this parameter refers to the selection of text horizontal alignment. There are three options {center ',' left ', right}. The default value is' center'
Vertical alignment, VA: this parameter refers to the selection of text vertical alignment. There are four options {top ',' center ',' bottom ',' baseline}. The default value is' top '
fontsize, size: this parameter refers to the size of the text. The default value is based on the setting of rcParams ["figure. Title"] (default: 'large')
fontweight, weight: this parameter is used to set the word weight. The default value is based on the setting of rcParams: rcParams ["figure.titleweight"] (default: 'normal')
fontproperties : None or dict, this parameter is optional. If this parameter is specified, the font size will be extracted from the default value of this parameter.
Return value
Returns the text as the created title instance.

4.1.4. xlabel and ylabel

pyplot API:

  • matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
  • matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None,*, loc=None, **kwargs)

OO API:

  • Axes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
  • Axes.set_ylabel(self, ylabel, fontdict=None, labelpad=None,*, loc=None, **kwargs)

parameter
xlabel or ylabel: the text of the label
labelpad: sets the distance from the label to the axis
loc: {left ',' center ',' right '}. The default is center
**kwargs:text attribute
Return value
Returns the text as the created xlabel and ylabel instances.

Text attributes can be entered either through * * kwargs attribute or by operating matplotlib.font_ The manager.fontproperties method. For example:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np

x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)

# Instantiate font using FontProperties
font = FontProperties()
font.set_family('serif')
font.set_name('Times New Roman')
font.set_style('italic')

fig, ax = plt.subplots(figsize=(5, 3))
fig.subplots_adjust(bottom=0.15, left=0.2)
ax.plot(x1, y1)
ax.set_xlabel('time [s]', fontsize='large', fontweight='bold') # Direct use * * kwargs
ax.set_ylabel('Damped oscillation [V]', fontproperties=font) # font after instantiation with FontProperties

plt.show()

4.1.5. font_manager

Font settings are the same as the above examples. Generally, there are two methods: Global font settings and custom local font settings. The following points should be noted:

'''see matplotlib All fonts in'''
from matplotlib import font_manager
font_family = font_manager.fontManager.ttflist
font_name_list = [i.name for i in font_family]
for font in font_name_list:
    print(f'{font}\n')
'''Global font attribute modification'''
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimSun']    # Specifies that the default font is new Tahoma.
plt.rcParams['axes.unicode_minus'] = False      # Solve the problem that the minus sign '-' is displayed as a square and an error is reported when saving the image.
'''Modification method of local font 1'''
import matplotlib.pyplot as plt
import matplotlib.font_manager as fontmg

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
plt.plot(x, label='Small sample drawing label')

# Use the font name directly.
plt.xlabel('x Axis name parameter', fontproperties='Microsoft YaHei', fontsize=16)         # Set the x-axis name in Microsoft elegant black font
plt.ylabel('y Axis name parameter', fontproperties='Microsoft YaHei', fontsize=14)         # Sets the Y axis name
plt.title('Title of coordinate system',  fontproperties='Microsoft YaHei', fontsize=20)         # Sets the font for the coordinate system title
plt.legend(loc='lower right', prop={"family": 'Microsoft YaHei'}, fontsize=10)    # Font setting of small sample diagram
'''Modification method of local font 2'''
import matplotlib.pyplot as plt
import matplotlib.font_manager as fontmg

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
plt.plot(x, label='Small sample drawing label')
#fname is the font library path in your system
my_font1 = fontmg.FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf')      # Read the bold font in the system.
my_font2 = fontmg.FontProperties(fname=r'C:\Windows\Fonts\simkai.ttf')      # Read the italics font in the system.
# fontproperties sets the Chinese display, and fontsize sets the font size
plt.xlabel('x Axis name parameter', fontproperties=my_font1, fontsize=16)       # Sets the x-axis name
plt.ylabel('y Axis name parameter', fontproperties=my_font1, fontsize=14)       # Sets the Y axis name
plt.title('Title of coordinate system',  fontproperties=my_font2, fontsize=20)       # Font settings for titles
plt.legend(loc='lower right', prop=my_font1, fontsize=10)              # Font setting of small sample diagram

4.1.6. mathtext

Use mathematical expressions in text labels. For an overview of MathText, see Write mathematical expressions . Its mathematical expression is similar to the grammatical expression in markdown and latex.

4.2. Text on tick

Setting tick and tick label is also a common step in visualization. matplotlib not only provides the mode of automatically generating scale and scale label, but also provides many ways for users to set flexibly.

4.2.1. Simple mode

You can use the set of axis_ The ticks method manually sets the label position, using the set of axis_ The ticklabels method formats the label manually

import matplotlib.pyplot as plt
import numpy as np
import matplotlib
x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
'''use axis of set_ticks Method to manually set the label'''
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
axs[0].plot(x1, y1)
axs[1].plot(x1, y1)
axs[1].xaxis.set_ticks(np.arange(0., 10.1, 2.))
plt.show()

'''use axis of set_ticklabels Method to manually set the label'''
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
axs[0].plot(x1, y1)
axs[1].plot(x1, y1)
ticks = np.arange(0., 8.1, 2.)
tickla = [f'{tick:1.2f}' for tick in ticks]
axs[1].xaxis.set_ticks(ticks)
axs[1].xaxis.set_ticklabels(tickla)
plt.show()

4.2.2. Tick Locators and Formatters

Axis.set_major_locator and Axis.set_minor_locator Method can be used to set the position of the label.
Axis.set_major_formatter and Axis.set_minor_formatter Method to format the label.
The advantage of this approach is that there is no need to explicitly list the scale values. set_major_formatter and set_minor_formatter these two formatter format commands can receive string format (matplotlib.ticker.StrMethodFormatter) or function parameter (matplotlib.ticker.FuncFormatter) to format the scale value.

4.3 legend

Legend common terms:

  • Legend entries: a legend consists of one or more legend entries. An entry consists of a key and a label.
  • legend key: the colored/patterned marker on the left side of each legend label
  • legend label: text describing the handle represented by the key
  • legend handle: the original object used to generate the appropriate legend entry in the legend

Take the following figure as an example, there are two legend entries in the box on the right; Two legend key s, one blue and one yellow respectively; Two legend label s, one named 'Line up' and one named 'Line Down'

Several common parameters:

(1) Set column position

plt.legend(loc = 'upper center') is equivalent to plt.legend(loc=9)

2) Set legend font size

fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}

(3) Set legend border and background

plt.legend(loc = 'best', frameon=False) # remove the legend border
plt.legend(loc = 'best', edgecolor = 'blue') # sets the legend border color
plt.legend(loc = 'best', facecolor = 'blue') # sets the background color of the legend. If there is no border, the parameter is invalid

(4) Set legend title

legend = plt.legend(["CH", "US"], title='China VS Us')

(5) Set legend name and corresponding relationship

legend = plt.legend([p1, p2], ["CH", "US"])

task

Try to use the functions mentioned in a picture to design title, text, xlabel, ylabel, mathematical expression, tick and ticklabel and legend in detail.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

plt.rcParams['font.sans-serif'] = ['SimSun']
plt.rcParams['axes.unicode_minus'] = False

font1 = {'family': 'SimSun',
         'alpha':0.7,
        'color':  'purple',
        'weight': 'normal',
        'size': 16,
        }
font2 = {'family': 'Times New Roman',
        'color':  'red',
        'weight': 'normal',
        'size': 16,
        }
font3 = {'family': 'serif',
        'color':  'blue',
        'weight': 'bold',
        'size': 14,
        }

font4 = {'family': 'Calibri',
        'color':  'navy',
        'weight': 'normal',
        'size': 17,
        }

x = np.linspace(0.0, 5.0, 100)
y = np.cos(2*np.pi*x) * np.exp(-x/3)

plt.plot(x, y, '--',label='curve')
plt.title('task', fontdict=font1)

plt.text(2, 0.65, r'$\cos(2 \pi x) \exp(-x/3)$', fontdict=font2)

plt.xlabel('Y=time (s)', fontdict=font3)
plt.ylabel('X=voltage(mv)', fontdict=font4)
plt.xlim(-0.5,5.5)

plt.legend()
plt.show()

Tags: Machine Learning neural networks Deep Learning data visualization

Posted on Fri, 26 Nov 2021 22:46:14 -0500 by harnacks