python 添加图例

Adding legend is the best way to label data series plotted on a graph. Matplotlib has an inbuilt defined function for our adding legend operation. The legend can be added to any type of plot such as line plot, dot plot, scatter plot, bar plot, etc. Following are some examples showing the implementation of matplotlib.pyplot.legend().

添加图例是标记图上绘制的数据系列的最佳方法。 Matplotlib有一个内置的定义函数,用于添加图例操作。 可以将图例添加到任何类型的绘图中,例如线图, 点图散点图 ,条形图等。以下是一些示例,显示了matplotlib.pyplot.legend()的实现。

Python | Adding legend to a Plot (1)
Python | Adding legend to a Plot (2)
Python | Adding legend to a Plot (3)

References: https://matplotlib.org/, https://in.mathworks.com/

参考: https : //matplotlib.org/,https : //in.mathworks.com/

用于将图例添加到图的Python代码 (Python code for adding legend to a plot)

# Data Visualization using Python
# Adding a Legend

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2, 100)

# Example 1
plt.figure()
plt.plot(x, x+2, label='linear')  
plt.plot(x, x**2, label='quadratic')  
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Legend Example 1")
plt.legend()

# Example 2
plt.figure()
x = np.linspace(0.0, 5.0)
y = x*x
plt.subplot(2, 1, 2)
plt.plot(x, y, 'g.-',label='quadratic')
plt.plot(x,x, 'r.-', label='linear')
plt.title('Legend Example 2')
plt.xlabel('numbers')
plt.ylabel('Square')
plt.legend()
plt.show()

# Example 3
# Random Bar Graph Example
plt.figure()
plt.barh(np.arange(26), np.random.randint(0,50,26), alpha = 0.5, color='r', label='Legend Bar Graph')
plt.title('Horizontal Bar Graph : Random')
plt.legend()

Output:

输出:

Output is as figure


翻译自: https://www.includehelp.com/python/adding-legend-to-a-plot.aspx

python 添加图例

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐