以下是一个使用Python和Matplotlib库比较两列数据的条形图的示例代码:
import matplotlib.pyplot as plt
# 定义两列数据
column1 = [10, 15, 20, 25, 30]
column2 = [5, 8, 12, 18, 20]
# 创建条形图
plt.bar(range(len(column1)), column1, label='Column 1')
plt.bar(range(len(column2)), column2, label='Column 2')
# 添加标题和标签
plt.title('Comparison of Two Columns')
plt.xlabel('Index')
plt.ylabel('Value')
# 添加图例
plt.legend()
# 显示图形
plt.show()
在这个示例中,我们通过plt.bar()
函数分别创建了两个条形图,分别代表两列数据。range(len(column1))
用于确定每个条形图的位置。label
参数用于添加图例。plt.title()
、plt.xlabel()
和plt.ylabel()
函数用于添加标题和标签。
最后,使用plt.show()
函数显示图形。