如何使用输入的*.txt文件绘制一个简单的条形图(Python,Matplotlib)?
要从输入的文本文件绘制一个非常简单的条形图,我们可以按以下步骤进行 −
- 为 条形名称 和 高度 创建一个空列表。
-
读取文本文件并遍历每一行。
-
将 名称 和 高度 附加到列表中。
-
使用 列表 (第一步)绘制 条形图 。
-
要显示图形,请使用 show() 方法。
示例
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
bar_names = []
bar_heights = []
for line in open("test_data.txt", "r"):
bar_name, bar_height = line.split()
bar_names.append(bar_name)
bar_heights.append(bar_height)
plt.bar(bar_names, bar_heights)
plt.show()
“ test_data.txt ”包含以下数据 −
Javed 75
Raju 65
Kiran 55
Rishi 95