matplotlib柱状图添加多重图例
时间: 2023-09-26 11:14:16 浏览: 30
可以使用`label`参数添加多个图例,然后使用`legend`函数进行设置。
以下是一个示例代码:
```python
import matplotlib.pyplot as plt
# 数据
categories = ['A', 'B', 'C', 'D']
values1 = [10, 20, 30, 40]
values2 = [15, 25, 35, 45]
# 绘制柱状图
plt.bar(categories, values1, label='Series 1')
plt.bar(categories, values2, bottom=values1, label='Series 2')
# 设置图例
plt.legend(loc='upper left')
plt.legend(loc='upper right')
# 显示图形
plt.show()
```
在这个例子中,我们首先绘制了两个柱状图,然后分别给它们设置了标签。最后,我们使用`legend`函数显示两个图例,分别位于左上角和右上角。
相关问题
python matplotlib柱状图添加图例
在python的matplotlib中,要为柱状图添加图例,可以使用`plt.legend()`函数。该函数会自动为图例中的每个柱子添加一个标签。
以下是一个简单的示例代码,展示了如何使用matplotlib创建柱状图并添加图例:
```python
import matplotlib.pyplot as plt
# 柱状图数据
x = [1, 2, 3, 4, 5]
y1 = [10, 15, 7, 12, 9]
y2 = [8, 11, 9, 14, 6]
# 创建柱状图
plt.bar(x, y1, label='柱状图1')
plt.bar(x, y2, label='柱状图2')
# 添加图例
plt.legend()
# 显示图形
plt.show()
```
在这个例子中,我们使用`plt.bar()`函数创建了两个柱状图,分别用`y1`和`y2`的数据表示。然后,使用`plt.legend()`函数添加了图例,它会自动为柱子添加标签。
matplotlib柱状图添两个图例
要在 matplotlib 柱状图中添加两个图例,可以使用 `ax.legend()` 函数来实现。以下是一个示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.arange(5)
y1 = np.array([2, 5, 4, 3, 6])
y2 = np.array([1, 3, 2, 4, 5])
labels1 = ['A', 'B', 'C', 'D', 'E']
labels2 = ['F', 'G', 'H', 'I', 'J']
# 绘制柱状图
fig, ax = plt.subplots()
ax.bar(x, y1, label='Group 1')
ax.bar(x, y2, bottom=y1, label='Group 2')
# 设置图例
leg1 = ax.legend(loc='upper left', frameon=True, title='Group 1')
leg2 = ax.legend(loc='upper right', frameon=True, title='Group 2')
ax.add_artist(leg1)
# 设置轴标签和标题
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_title('Two Legends Bar Chart')
plt.show()
```
在此示例中,我们使用 `ax.bar()` 函数绘制了两组柱状图,并使用 `label` 参数为它们分别设置了标签。然后,我们使用 `ax.legend()` 函数分别为每组柱状图创建了一个图例,并使用 `loc` 参数设置了它们的位置。注意,我们需要通过 `ax.add_artist()` 函数将第一个图例添加回轴对象,以便两个图例可以共存。
最后,我们使用 `ax.set_xlabel()` 和 `ax.set_ylabel()` 函数设置 x 和 y 轴标签,使用 `ax.set_title()` 函数设置图表标题。运行此代码将生成一个带有两个图例的柱状图。