Matplotlib子图中的图例
在本教程中,我们将学习如何使用Matplotlib在子图中包含图例。可以在创建图表后使用legend()函数添加图例。
语法:
子图中图例的语法是:
axes[position].legend(loc = '')
在此示例中,我们将使用对数和指数子图绘制散点图:
# First, we will import the required modules
from matplotlib import pyplot as PPlt
import numpy as nmp
# here we will assign the value to x axis
x_axis1 = nmp.arange(2, 22, 1.5)
# Now, we will get the value of log10
y_axis_log10_1 = nmp.log10(x_axis)
# then, we will get the value of exponential
y_axix_exp1 = nmp.exp(x_axis)
# Here, we will create subplots by using subplot() function
fig, axes = PPlt.subplots(2)
# now, we will depicte the visualization
axes[0].plot(x_axis1, y_axis_log10_1, color = 'Red', label = "log10")
axes[1].plot(x_axis1, y_axix_exp1, color = 'Pink', label = "exponential")
# Here, we will select the position at which legend to be added
axes[0].legend(loc = 'best')
axes[1].legend(loc = 'best')
# At last, we will display the plot
PPlt.show()
输出
示例2:
在此示例中,我们将使用正弦和余弦的subplot绘制散点图:
# First, we will import the required modules
from matplotlib import pyplot as PPlt
import numpy as nmp
# here we will assign the value to x axis
x_axis1 = nmp.arange(-2, 3, 0.5)
# Now, we will get the value of sine
y_axis_sine1 = nmp.sin(x_axis)
# Now, we will get the value of cos
y_axix_cose1 = nmp.cos(x_axis)
# Here, we will create subplots by using subplot() function
fig, axes = PPlt.subplots(2)
# now, we will depicte the visualization
axes[0].scatter(x_axis1, y_axis_sine1, color = 'Red', marker = '*', label = "sine")
axes[1].scatter(x_axis1, y_axix_cose1, color = 'Black', marker = '*', label = "cos")
# Here, we will select the position at which legend to be added
axes[0].legend(loc = 'best')
axes[1].legend(loc = 'best')
# At last, we will display the plot
PPlt.show()
输出
示例3:
在这个示例中,我们将使用子图绘制散点图 (y = x^2) 和 (y = x^3):
# First, we will import the required modules
from matplotlib import pyplot as PPlt
# here we will assign value to x axis
x_axis = list(range(-15, 15))
# here, we will get the value of x * x
y_axis_1 = [x * x for x in x_axis]
# here, we will get the value of x * x * x
y_axix_2 = [x * x * x for x in x_axis]
# Now, we will create subplots by using subplot() function
fig, axes = PPlt.subplots(2)
# Now, we will depicte the visualization
axes[0].scatter(x_axis, y_axis_1, color = 'Blue', marker = '*', label = "y = x ^ 2")
axes[1].scatter(x_axis, y_axix_2, color = 'Brown', marker = '*', label = "y = x ^ 3")
# Here, we will select the position at which legend to be added
axes[0].legend(loc = 'upper center')
axes[1].legend(loc = 'upper left')
# At last, we will display the plot
PPlt.show()
输出
结论
在本教程中,我们讨论了如何使用不同方法在matplotlib图表的子图中使用图例。