matplotlib 一个柱状图添两个图例
时间: 2023-11-20 08:06:42 浏览: 43
要在 matplotlib 中为柱状图添加两个图例,可以使用以下代码:
```python
import matplotlib.pyplot as plt
# 生成数据
x = [1, 2, 3, 4, 5]
y1 = [10, 8, 6, 4, 2]
y2 = [8, 6, 4, 2, 0]
# 绘制柱状图
fig, ax = plt.subplots()
rects1 = ax.bar(x, y1, label='Data 1')
rects2 = ax.bar(x, y2, label='Data 2', alpha=0.5)
# 添加第一个图例
ax.legend(loc='upper left')
# 创建第二个图例
lines = [ax.plot([], [], color=c, linewidth=3)[0] for c in ['blue', 'orange']]
labels = ['Data 1', 'Data 2']
ax2 = ax.twinx()
ax2.legend(lines, labels, loc='upper right')
# 显示图形
plt.show()
```
该代码将创建一个柱状图,并在其上添加两个图例。第一个图例位于图形的左上角,显示有关柱状图的所有信息。第二个图例位于图形的右上角,显示每个数据系列的颜色和标签。注意,第二个图例是通过创建一个新的 `twinx` 坐标轴来实现的,并通过在该坐标轴上绘制虚线来表示每个数据系列。
相关问题
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()` 函数设置图表标题。运行此代码将生成一个带有两个图例的柱状图。
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()`函数添加了图例,它会自动为柱子添加标签。