如何在 Matplotlib 中删除图例
我们可以使用图例对象的 remove()
和 set_visible()
方法从 Matplotlib 中的图形中删除图例。我们还可以通过以下方式从 Matplotlib 中的图形中删除图例:将 plot()
方法中的 label
设置为 _nolegend_
,将 axes.legend
设置为 None
以及将 figure.legends
设置为空列表。
matplotlib.axes.Axes.get_legend().remove()
我们可以使用 matplotlib.axes.Axes.get_legend().remove()
方法从 Matplotlib 中的图形中删除图例。
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-3,3,100)
y1=np.exp(x)
y2=3*x+2
fig, ax = plt.subplots(figsize=(8,6))
ax.plot(x, y1, c='r', label='expoential')
ax.plot(x, y2, c='g', label='Straight line')
leg = plt.legend()
ax.get_legend().remove()
plt.show()
输出:
matplotlib.axes.Axes.get_legend().set_visible()
如果我们将 False
作为参数传递给 matplotlib.axes.Axes.get_legend().set_visible()
方法,则可以从 Matplotlib 中的图形中删除图例。
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-3,3,100)
y1=np.exp(x)
y2=3*x+2
fig, ax = plt.subplots(figsize=(8,6))
ax.plot(x, y1, c='r', label='expoential')
ax.plot(x, y2, c='g', label='Straight line')
leg = plt.legend()
ax.get_legend().set_visible(False)
plt.show()
输出:
此方法实际上将图例设置为不可见,但不会删除图例。
matplotlib.axes.Axes.plot()
方法中的 label=_nolegend_
参数
在 matplotlib.axes.Axes.plot()方法中将 label=_nolegend_
作为参数传递也会从 Matplotlib 的图形中删除图例。
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-3,3,100)
y1=np.exp(x)
y2=3*x+2
fig, ax = plt.subplots(figsize=(8,6))
leg = plt.legend()
ax.plot(x, y1, c='r', label='_nolegend_')
ax.plot(x, y2, c='g', label='_nolegend_')
plt.show()
输出:
将 axis
对象的 legend_
属性设置为 None
将 axis
对象的 legend_
属性设置为 None
可以从 Matplotlib 中的图形中删除图例。
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-3,3,100)
y1=np.exp(x)
y2=3*x+2
fig, ax = plt.subplots(figsize=(8,6))
leg = plt.legend()
ax.plot(x, y1, c='r', label='expoential')
ax.plot(x, y2, c='g', label='Straight line')
plt.gca.legend_ =None
plt.show()
输出:
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串