matplotlib 条形图常见用法示例
时间: 2023-06-24 15:07:38 浏览: 94
下面是一个使用 matplotlib 绘制条形图的常见示例:
```python
import matplotlib.pyplot as plt
# 数据
labels = ['A', 'B', 'C', 'D', 'E']
values = [10, 15, 20, 25, 30]
# 绘图
plt.bar(labels, values)
# 设置标题和标签
plt.title('Bar Chart Example')
plt.xlabel('Categories')
plt.ylabel('Values')
# 显示图形
plt.show()
```
上述代码会生成一个简单的条形图,其中 x 轴为类别标签,y 轴为数值。
除了上述基本的条形图外,还可以根据需要设置更多的属性,比如颜色、宽度、边框等。以下是一个更完整的示例代码:
```python
import matplotlib.pyplot as plt
# 数据
labels = ['A', 'B', 'C', 'D', 'E']
values1 = [10, 15, 20, 25, 30]
values2 = [5, 10, 15, 20, 25]
# 绘图
fig, ax = plt.subplots()
rects1 = ax.bar(labels, values1, color='b', width=0.5, edgecolor='black', linewidth=1, alpha=0.8)
rects2 = ax.bar(labels, values2, color='r', width=0.3, edgecolor='black', linewidth=1, alpha=0.8)
# 设置标题和标签
ax.set_title('Bar Chart Example')
ax.set_xlabel('Categories')
ax.set_ylabel('Values')
# 设置图例
ax.legend((rects1[0], rects2[0]), ('Data1', 'Data2'))
# 显示图形
plt.show()
```
这个示例中有两组数据,分别用不同的颜色表示,并且在图例中进行了标注。同时还设置了条形的宽度、边框和透明度等属性。
阅读全文
相关推荐
















