Matplotlib drawing | Tips for quickly defining chart styles

Matpltlibrc file set chart properties

In the drawing process of Matplotlib, every time a chart is created, the style (such as font size, color, resolution, horizontal and vertical scale, horizontal and vertical coordinates) in the chart must be set once. Repeating is tedious. The following shows a Sine function curve sin ⁡ (θ) \sin(\theta)sin ( θ )

X =np.linspace(-np.pi,np.pi,256,endpoint =True)
S = np.sin(X)


plt.plot(X,S,color = "blue",linewidth = 3.0,linestyle = ":")

Snipaste_2020-07-18_13-52-03.png

For convenience, matplotlib provides a matplotlibrc file interface to customize chart properties globally (chart size, DPI, line width, axis, style, grid properties, etc.). The method of use is the rcParams command, which is defined once, and is created for the next All of the chart styles are effective, avoiding the trouble of callback parameters

rcParsms parameters are declared in the form of dictionary key-value pairs, the format is as follows

matplotlib.rcParams['lines.linewidth'] = 2
matplotlib.rcParams['lines.linestyle'] = '--'

Before creating the chart, set the global parameters. After the settings are set, they can be applied to all charts, without the need to set them one by one.

mpl.rcParams['lines.linewidth'] = 2.5 #linewidth
mpl.rcParams['lines.linestyle'] = '-' #( mpl 是 matplotlib 的缩写)
plt.plot(X,S,color = 'red')

Snipaste_2020-07-18_13-52-39.png

An abbreviation of matplotlib.rcParams mentioned above is the mpl.rc() function

mpl.rc('lines', linewidth=4, linestyle='-.')
plt.plot(X,S,color = 'red')

If you don’t want to use the previously set global style, you can also set it separately when drawing the chart. In this way, the original style will be overwritten directly. For example, only the line style is changed here, linewidth is set to "-.", and the color is set to orange , Other parameters remain unchanged:

Snipaste_2020-07-18_14-20-51.png

In addition to the common attribute settings mentioned above, you can also use rcParams to change the coordinate label, size, and scale color of the horizontal axis;

mpl.rcParams['axes.grid'] =True
mpl.rcParams['axes.labelsize'] = 15
mpl.rcParams['axes.labelcolor'] ="red"

mpl.rcParams['xtick.color'] = 'red'
mpl.rcParams['xtick.alignment'] = "center"


plt.plot(X,S,color = 'orange')
plt.ylabel("Y")
plt.xlabel("X")

Snipaste_2020-07-18_14-42-51.png

According to the official website, rcParam also supports FONT, LaTex, TEXT, IMAGES, ANIMATION and other types of attribute modification, which is enough for daily drawing needs.

## Matplotlib configuration are currently divided into following parts:
##     - BACKENDS
##     - LINES
##     - PATCHES
##     - HATCHES
##     - BOXPLOT
##     - FONT
##     - TEXT
##     - LaTeX
##     - AXES
##     - DATES
##     - TICKS
##     - GRIDS
##     - LEGEND
##     - FIGURE
##     - IMAGES
##     - CONTOUR PLOTS
##     - ERRORBAR PLOTS
##     - HISTOGRAM PLOTS
##     - SCATTER PLOTS
##     - AGG RENDERING
##     - PATHS
##     - SAVING FIGURES
##     - INTERACTIVE KEYMAPS
##     - ANIMATION

For specific details, please refer to the official website document: https://matplotlib.org/tutorials/introductory/customizing.html

Matplotlib set style style

I have seen some of the visualization packages ggplot2 and recarts in the R language. Compared with matplotlib, I feel that the visualization effect of matplotlib is a little bit worse. The following figure is a chart drawn by ggplot

Snipaste_2020-07-18_15-25-13.png

If you study carefully, matplotlib is actually very good in terms of visualization. matlibplot provides a very powerful style modification and switching mechanism. For example, if we see a certain chart style is good, we can save it as a style file and set it to matplibplot calls the interface, you only need to fill in the data when you draw the same style chart next time, call it

Before defining the style, you can preview the types of chart styles provided by matplotlib. There are 26 styles in matplotlib 3.1.1.

print(plt.style.available)

#print
['bmh',
 'classic',
 'dark_background',
 'fast',
 'fivethirtyeight',
 'ggplot',
 'grayscale',
 'seaborn-bright',
 'seaborn-colorblind',
 'seaborn-dark-palette',
 'seaborn-dark',
 'seaborn-darkgrid',
 'seaborn-deep',
 'seaborn-muted',
 'seaborn-notebook',
 'seaborn-paper',
 'seaborn-pastel',
 'seaborn-poster',
 'seaborn-talk',
 'seaborn-ticks',
 'seaborn-white',
 'seaborn-whitegrid',
 'seaborn',
 'Solarize_Light2',
 'tableau-colorblind10',
 '_classic_test']

Use built-in styles

The style is relatively simple to use, one line of code is enough, the style set here takes ggplot as an example

plt.style.use("ggplot")

S = np.cos(X)
plt.plot(X,S)

Snipaste_2020-07-18_15-38-51.png

Mixed style use

In addition to being able to use a single style, matplotlib can also mix multiple styles together and store the style names as a list; but during use, if the attributes of multiple styles conflict (a style background is black, One background is white), the style on the right of the list will cover the left;

plt.style.use(['fivethirtyeight','dark_background'])

S = np.cos(X)
plt.plot(X,S)

Snipaste_2020-07-18_17-04-41.png

Custom style

You can also define the style by yourself. The attributes in the style are defined in the following way and stored

axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16

After the attributes are defined, they are stored in a file, and the file name format needs to be required: the suffix is ​​.mplstyle; when calling, use the pyplot.use.style("your style file path") command.

>>> import matplotlib.pyplot as plt
>>> plt.style.use('./images/presentation.mplstyle')

Temporary chart style

It should be noted that the above mentioned that the plt.style.use() command is used to set the global style. After the chart is created later, the default style used is the same; Matplotlib is here to set the complete pattern for a certain chart Want to set to a specific style, added the concept of temporary style:

with plt.style.context('dark_background'):
    plt.plot(np.sin(np.linspace(0, 2 * np.pi)))
plt.show()

In the above method, a temporary style is created with with, and the plt.style.context() function is used. The created style is limited in scope and is only valid for chart formats created within the scope of with

Snipaste_2020-07-18_17-06-12.png

Guess you like

Origin blog.csdn.net/weixin_42512684/article/details/107604216