English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Matplotlib Axis Formatting

Matplotlib axis formatting detailed operation tutorial

Sometimes one or more points are much larger than a large amount of data. In this case, the axis scale needs to be set to logarithmic (log) instead of normal proportion. This is logarithmic scale. In Matplotlib, the xscale or vscale attribute of the axes object can be set to log.

Sometimes it is necessary to display some additional distance between the axis number and the axis label. The labelpad attribute of any axis (x or y or both) can be set to the required value.

The above two functions are demonstrated with the help of the following examples. The right subplot has a logarithmic scale, and the left subplot has a more distant label on the x-axis.

Reference the following example code:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
#! /usr/bin/env python
 #coding=utf-8
 import matplotlib.pyplot as plt
 import numpy as np
 import math
 # Display Chinese settings...
 plt.rcParams['font.sans-serif'] = ['SimHei']  # Step one (replacement of sans-serif font)
 plt.rcParams['axes.unicode_minus'] = False  # Step Two (Solve the problem of displaying negative signs of negative numbers on the coordinate axis)
 fig, axes = plt.subplots(1, 2, figsize=(10,4))
 x = np.arange(1,5)
 axes[0].plot( x,  np.exp(x))
 axes[0].plot(x,x**2)
 axes[0].set_title("Normal proportion")
 axes[1].plot(x,  np.exp(x))
 axes[1].plot(x,  x**2)
 axes[1].set_yscale("log")
 axes[1].set_title("Logarithmic scale (y)")
 axes[0].set_xlabel("x axis")
 axes[0].set_ylabel("y axis")
 axes[0].xaxis.labelpad = 10
 axes[1].set_xlabel("x axis")
 axes[1].set_ylabel("y axis")
 plt.show()

Execute the above example code to get the following result -

The axis tip is the line connecting the axis scale line, dividing the boundary of the plotting area. The tip of the axis object is located at the top, bottom, left, and right. Each tip can be formatted by specifying color and width. If any edge color is set to none, it can be made invisible.

Reference example code:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
#! /usr/bin/env python
 #coding=utf-8
 import matplotlib.pyplot as plt
 import numpy as np
 import math
 # Display Chinese settings...
 plt.rcParams['font.sans-serif'] = ['SimHei']  # Step one (replacement of sans-serif font)
 plt.rcParams['axes.unicode_minus'] = False  # Step Two (Solve the problem of displaying negative signs of negative numbers on the coordinate axis)
 fig = plt.figure()
 ax=plt.subplot(111)
 ax.spines['bottom'].set_color('blue')
 ax.spines['left'].set_color('red')
 ax.spines['left'].set_linewidth(2)
 ax.spines['right'].set_color(None)
 ax.spines['top'].set_color(None)
 ax.plot([1,2,3,4,5))
 plt.show()#