绘制两组数据柱形图的代码
时间: 2023-06-11 07:06:31 浏览: 60
以下是Python中使用matplotlib库绘制两组数据柱形图的代码示例:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.array([1, 2, 3, 4, 5]) # x轴数据
y1 = np.array([10, 8, 6, 4, 2]) # 第一组y轴数据
y2 = np.array([5, 4, 3, 2, 1]) # 第二组y轴数据
# 绘制柱形图
plt.bar(x-0.2, y1, 0.4, label='Group 1')
plt.bar(x+0.2, y2, 0.4, label='Group 2')
# 添加图例
plt.legend()
# 添加标签和标题
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Two Groups Bar Chart')
# 显示图形
plt.show()
```
该代码中使用了numpy库生成了两组数据,然后使用matplotlib中的`bar`函数绘制了两组数据柱形图,其中参数`x-0.2`和`x+0.2`表示两组柱形图在x轴上的位置,`0.4`表示柱形图的宽度。最后添加了标签和标题,并显示图形。
相关问题
matplotlib中用单子图绘制多组柱形图
是的,您可以使用 Matplotlib 中的 `bar` 函数来绘制柱形图。如果您要在同一个子图中绘制多组柱形图,可以使用 `numpy` 库来生成多组数据,然后在同一个子图中调用 `bar` 函数。
以下是一个示例代码,用于绘制两组柱形图:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成数据
x = np.array([1, 2, 3, 4, 5])
y1 = np.array([5, 8, 3, 6, 4])
y2 = np.array([3, 5, 2, 7, 1])
# 创建子图
fig, ax = plt.subplots()
# 绘制第一组柱形图
ax.bar(x-0.2, y1, width=0.4, color='b', align='center')
# 绘制第二组柱形图
ax.bar(x+0.2, y2, width=0.4, color='g', align='center')
# 设置 x 轴标签
ax.set_xticks(x)
ax.set_xticklabels(['A', 'B', 'C', 'D', 'E'])
# 设置图例
ax.legend(['Group 1', 'Group 2'])
# 显示图形
plt.show()
```
运行上述代码,您将得到一个包含两组柱形图的子图。其中,每组柱形图由不同的颜色表示,图例标注了每组柱形图的名称。
matplotlib并列柱形图编写代码
以下是使用Matplotlib绘制并列柱形图的代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
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_xlabel('Group')
ax.set_ylabel('Scores')
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()
```
运行上述代码将生成一个并列柱形图,其中包含两组数据,每组数据包含五个柱子。
注:本例中的数据是随机生成的。您可以根据实际需求更改数据。