如何在 Matplotlib 中绘制对数轴?
使用 Matplotlib 的所有绘图中的轴默认都是线性的,matplotlib.pyplot 库的 yscale() 和 xscale() 方法可用于分别将 y 轴或 x 轴刻度更改为对数。
方法 yscale() 或 xscale() 将单个值作为参数,该值是刻度的转换类型,为了将轴转换为对数刻度,我们传递“log”关键字或 matplotlib.scale。 LogScale 类到 yscale 或 xscale 方法。
xscale 方法语法:
Syntax : matplotlib.pyplot.xscale(value, **kwargs)
Parameters:
- Value = { “linear”, “log”, “symlog”, “logit”, … }
- **kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale)
Returns : Converts the x-axes to the given scale type. (Here we use the “log” scale type)
yscale 方法语法:
Syntax: matplotlib.pyplot.yscale(value, **kwargs)
Parameters:
- value = { “linear”, “log”, “symlog”, “logit”, … }
- **kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale)
Returns : Converts the y-axes to the given scale type. (Here we use the “log” scale type)
下面给出了分别将 y 轴和 x 轴转换为对数刻度的实现。
示例 1:没有对数轴。
Python3
import matplotlib.pyplot as plt
# exponential function y = 10^x
data = [10**i for i in range(5)]
plt.plot(data)
Python3
import matplotlib.pyplot as plt
# exponential function y = 10^x
data = [10**i for i in range(5)]
# convert y-axis to Logarithmic scale
plt.yscale("log")
plt.plot(data)
Python3
import matplotlib.pyplot as plt
# exponential function x = 10^y
datax = [ 10**i for i in range(5)]
datay = [ i for i in range(5)]
#convert x-axis to Logarithmic scale
plt.xscale("log")
plt.plot(datax,datay)
输出:
示例 2: y 轴对数刻度。
蟒蛇3
import matplotlib.pyplot as plt
# exponential function y = 10^x
data = [10**i for i in range(5)]
# convert y-axis to Logarithmic scale
plt.yscale("log")
plt.plot(data)
输出:
示例 3: x 轴对数刻度。
蟒蛇3
import matplotlib.pyplot as plt
# exponential function x = 10^y
datax = [ 10**i for i in range(5)]
datay = [ i for i in range(5)]
#convert x-axis to Logarithmic scale
plt.xscale("log")
plt.plot(datax,datay)
输出: