📜  如何在 Matplotlib 中将 Y 轴标签添加到次要 Y 轴?

📅  最后修改于: 2022-05-13 01:54:50.751000             🧑  作者: Mango

如何在 Matplotlib 中将 Y 轴标签添加到次要 Y 轴?

有时,在通过图表分析任何数据时,我们需要两个 x 或 y 轴来深入了解数据。 Python的 Matplotlib 库是最流行的数据可视化库,我们可以在 Matplotlib 中生成任何类型的绘图。我们可以创建一个具有两个 y 轴的图,并且可以为两个 y 轴提供不同的标签。我们可以在 twinx()函数的帮助下通过创建或使用两个不同的轴对象来绘制具有两个不同 y 轴的图。首先,我们创建图形和轴对象并制作第一个图。我们还在创建的轴对象的帮助下设置 x 和 y 轴标签。

Axes 对象: Axes 是创建子图的最基本和最灵活的单元。轴用于在图中的任何位置放置图。给定的绘图图形可以包含多个轴,但给定的轴对象只能位于绘图的一个图形中。

方法:

  • 导入包。
  • 使用轴对象并创建子图。
  • 使用 twinx() 定义绘图值。
  • 现在标记轴。
  • 显示情节。

示例 1:

在这个例子中,我们在 twinx()函数的帮助下使用两个不同的轴对象 a 和 a2 创建了一个具有两个不同 y 轴的图。 ax.twinx() 为与原始 y 轴相反的 y 轴创建一个新的 Axes 对象 ax2。第二个轴对象 ax2 用于绘制第二个 y 轴变量的图并更新其标签。

Python3
# Adding a Y-Axis Label to the Secondary Y-Axis in Matplotlib
# importing the libraries
import numpy as np
import matplotlib.pyplot as plt
 
# creating data for plot
# data arrangement between 0 and 50
# with the difference of 2
# x-axis
x = np.arange(0, 50, 2)
 
# y-axis values
y1 = x**2
 
# secondary y-axis values
y2 = x**3
 
# plotting figures by creating aexs object
# using subplots() function
fig, ax = plt.subplots(figsize = (10, 5))
plt.title('Example of Two Y labels')
 
# using the twinx() for creating another
# axes object for secondary y-Axis
ax2 = ax.twinx()
ax.plot(x, y1, color = 'g')
ax2.plot(x, y2, color = 'b')
 
# giving labels to the axises
ax.set_xlabel('x-axis', color = 'r')
ax.set_ylabel('y1-axis', color = 'g')
 
# secondary y-axis label
ax2.set_ylabel('Secondary y-axis', color = 'b')
 
# defining display layout
plt.tight_layout()
 
# show plot
plt.show()


Python3
# Adding a Y-Axis Label to the
# Secondary Y-Axis in Matplotlib
# importing the libraries
import numpy as np
import matplotlib.pyplot as plt
 
# creating data for plot
# data arrangement between 0 and 50 with the difference of 2
# x-axis values
x = np.arange(0, 50, 2)
 
#y-axis values
y1 = x**2
 
# secondary y-axis values
y2 = x**3
 
# plotting figures by creating aexs object
# using subplots() function
fig, ax = plt.subplots(figsize = (10, 5))
plt.title('Example of Two Y labels')
 
# using the twinx() for creating
# another axes object for secondary y-Axis
ax2 = ax.twinx()
# creating a bar plot
ax.bar(x, y1, color = 'g')
ax2.bar(x, y2, color = 'b')
 
# giving labels to the axises
ax.set_xlabel('x-axis', color = 'r')
ax.set_ylabel('y1-axis', color = 'g')
 
# secondary y-axis label
ax2.set_ylabel('Secondary y-axis', color = 'b')
 
# defining display layout
plt.tight_layout()
 
# show plot
plt.show()


Python3
# Adding a Y-Axis Label to
# the Secondary Y-Axis in Matplotlib
# importing the libraries
import pandas as pd
import matplotlib.pyplot as plt
 
#creating dataframe for plot
dataset = pd.DataFrame({'Name':['Rohit', 'Seema',
                                'Meena', 'Geeta',
                                'Rajat'],
                         
                   'Height': [155,129,138,164,145],
                   'Weight': [60,40,45,55,60]})
 
# creating axes object and defining plot
ax = dataset.plot(kind = 'line', x = 'Name',
                  y = 'Height', color = 'Blue',
                  linewidth = 3)
 
ax2 = dataset.plot(kind = 'line', x = 'Name',
                   y = 'Weight', secondary_y = True,
                   color = 'Red',  linewidth = 3,
                   ax = ax)
 
#title of the plot
plt.title("Student Data")
 
#labeling x and y-axis
ax.set_xlabel('Name', color = 'g')
ax.set_ylabel('Height', color = "b")
ax2.set_ylabel('Weight', color = 'r')
 
#defining display layout
plt.tight_layout()
 
#show plot
plt.show()


输出:

示例 2:

在本例中,我们使用相同的方法创建了一个条形图。

蟒蛇3

# Adding a Y-Axis Label to the
# Secondary Y-Axis in Matplotlib
# importing the libraries
import numpy as np
import matplotlib.pyplot as plt
 
# creating data for plot
# data arrangement between 0 and 50 with the difference of 2
# x-axis values
x = np.arange(0, 50, 2)
 
#y-axis values
y1 = x**2
 
# secondary y-axis values
y2 = x**3
 
# plotting figures by creating aexs object
# using subplots() function
fig, ax = plt.subplots(figsize = (10, 5))
plt.title('Example of Two Y labels')
 
# using the twinx() for creating
# another axes object for secondary y-Axis
ax2 = ax.twinx()
# creating a bar plot
ax.bar(x, y1, color = 'g')
ax2.bar(x, y2, color = 'b')
 
# giving labels to the axises
ax.set_xlabel('x-axis', color = 'r')
ax.set_ylabel('y1-axis', color = 'g')
 
# secondary y-axis label
ax2.set_ylabel('Secondary y-axis', color = 'b')
 
# defining display layout
plt.tight_layout()
 
# show plot
plt.show()

输出:

示例 3:

我们也可以在 Pandas 的第二个 y 轴上添加一个 y 轴标签。从 DataFrame 生成绘图,也不使用 twinx()函数。在这个例子中,我们将使用简单的 DataFrame.plot()函数和一些参数来指定绘图。

当我们在 DataFrame.plot 方法中将 secondary_y 参数设置为 True 时,它会返回可用于设置标签的不同轴。

蟒蛇3

# Adding a Y-Axis Label to
# the Secondary Y-Axis in Matplotlib
# importing the libraries
import pandas as pd
import matplotlib.pyplot as plt
 
#creating dataframe for plot
dataset = pd.DataFrame({'Name':['Rohit', 'Seema',
                                'Meena', 'Geeta',
                                'Rajat'],
                         
                   'Height': [155,129,138,164,145],
                   'Weight': [60,40,45,55,60]})
 
# creating axes object and defining plot
ax = dataset.plot(kind = 'line', x = 'Name',
                  y = 'Height', color = 'Blue',
                  linewidth = 3)
 
ax2 = dataset.plot(kind = 'line', x = 'Name',
                   y = 'Weight', secondary_y = True,
                   color = 'Red',  linewidth = 3,
                   ax = ax)
 
#title of the plot
plt.title("Student Data")
 
#labeling x and y-axis
ax.set_xlabel('Name', color = 'g')
ax.set_ylabel('Height', color = "b")
ax2.set_ylabel('Weight', color = 'r')
 
#defining display layout
plt.tight_layout()
 
#show plot
plt.show()

输出:

在上面的例子中,绘图是在没有使用 twinx()函数的情况下创建的,但我们已经创建了两个轴对象 ax 和 ax2,如其他示例中给出的两个 y 轴,以制作具有两个 y 轴的绘图并更新其标签。