python绘制双柱状图,右上角的图例怎么实现上下排列
时间: 2024-01-25 22:42:47 浏览: 22
可以使用Matplotlib库中的legend方法来实现上下排列的图例。具体代码如下:
```
import matplotlib.pyplot as plt
# 绘制柱状图
plt.bar([1, 2, 3], [4, 5, 6], label='A')
plt.bar([1, 2, 3], [7, 8, 9], label='B')
# 设置图例
plt.legend(loc='upper center', ncol=2, bbox_to_anchor=(0.5, -0.1))
# 显示图形
plt.show()
```
其中,`loc`参数设置图例的位置为上中,`ncol`参数设置图例的列数为2,`bbox_to_anchor`参数设置图例的位置偏移量,使得图例在图形外部。
相关问题
python绘制双柱状图
好的,可以使用Python中的Matplotlib库来绘制双柱状图。以下是一个简单的示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 数据
labels = ['A', 'B', 'C', 'D', 'E']
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
x = np.arange(len(labels))
width = 0.35
# 绘图
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')
# 添加轴标签、标题和图例
ax.set_ylabel('Scores')
ax.set_xlabel('Groups')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
# 添加数据标签
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
plt.show()
```
解释一下这段代码:
1. 导入必要的库:Matplotlib和NumPy。
2. 准备数据:这里我们有两组数据,每组数据都有5个元素,分别代表5个组的男女得分。
3. 创建x轴坐标和柱状图的宽度。
4. 使用Matplotlib的subplots()函数创建一个图形对象和一个轴对象。
5. 使用Matplotlib的bar()函数在轴对象上创建柱状图。
6. 添加轴标签、标题和图例。
7. 添加数据标签:这里使用Matplotlib的annotate()函数添加每个柱状图的数值标签。
8. 显示图形。
运行这段代码,你会看到一个双柱状图,其中每个组都有男女两种得分。
python绘制柱状图显示数值_Python实现绘制双柱状图并显示数值功能示例
好的,下面是Python实现绘制双柱状图并显示数值功能的示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 数据
labels = ['A', 'B', 'C', 'D', 'E']
data1 = [20, 35, 30, 35, 27]
data2 = [25, 32, 34, 20, 25]
# 设置柱状图宽度
bar_width = 0.3
# 计算偏移量
x_ticks = np.arange(len(labels))
offset = bar_width / 2
# 绘制柱状图
plt.bar(x_ticks - offset, data1, width=bar_width, label='Data 1')
plt.bar(x_ticks + offset, data2, width=bar_width, label='Data 2')
# 显示数值
for i in range(len(x_ticks)):
plt.text(x_ticks[i] - offset, data1[i] + 1, str(data1[i]))
plt.text(x_ticks[i] + offset, data2[i] + 1, str(data2[i]))
# 设置x轴标签
plt.xticks(x_ticks, labels)
# 设置图例
plt.legend()
# 显示图形
plt.show()
```
这段代码会生成一个双柱状图,并在每个柱状图上方显示对应的数值。您可以根据自己的需求修改数据、标签和其他参数来适应不同的情况。