怎么让这两个图例在一起
时间: 2024-02-20 15:59:35 浏览: 21
要将这两个图例合并为一个,可以使用ax.legend()函数将它们添加到同一个图层中。首先需要定义两个柱形的对象,然后在创建图例之前,将它们存储在一个列表中。接下来,使用ax.legend()函数并设置handles参数为柱形对象的列表,labels参数为相应的标签列表,以及loc参数来指定图例的位置。
以下是修改后的代码:
```
import matplotlib.pyplot as plt
# 数据
similarity = [0.3940893515407449, 1.0116279478167544]
divergence = [8.761, 24.455]
labels = ['w. cu', 'wo. cu']
# 设置字体大小
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 14
plt.rcParams['legend.fontsize'] = 12
# 柱形宽度和间隔
width = 0.3
x1_list = []
x2_list = []
for i in range(len(similarity)):
x1_list.append(i)
x2_list.append(i + width)
# 创建图层
fig, ax = plt.subplots()
# 设置左侧Y轴对应的figure
ax.set_ylabel('Time per iteration (s)')
ax.set_ylim(0, 1.1)
ax1 = ax.bar(x1_list, similarity, width=width, color='tab:red', align='edge', label='Similarity')
ax.set_xticklabels(ax.get_xticklabels())
# 设置右侧Y轴对应的figure
ax2 = ax.twinx()
ax2.set_ylabel('GPU Usage (GB)')
ax2.set_ylim(0, 28)
ax2.bar(x2_list, divergence, width=width, color='tab:blue', align='edge', tick_label=labels, label='Divergence')
# 合并图例
handles = [ax1, ax2]
labels = ['Similarity', 'Divergence']
ax.legend(handles=handles, labels=labels, loc='upper left')
# 显示图表
plt.tight_layout()
plt.savefig("similarity.png")
plt.show()
```
这将在图表中添加一个图例,显示“Similarity”和“Divergence”标签,并将它们与相应的柱形颜色匹配。注意,在创建柱形的过程中,需要将它们存储为对象,并在ax.legend()函数中使用它们来创建图例。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)