Python:从txt文件绘制数据

4
我该如何绘制这种数据的直方图?
10 apples
3 oranges
6 tomatoes
10 pears

从文本文件中读取?

谢谢


请查看matplotlib - Felix Kling
3个回答

6

以下是一种给条形图分配不同颜色的方法。它适用于任何数量的条形。

import numpy as np
import pylab
import matplotlib.cm as cm

arr = np.genfromtxt('data', dtype=None)
n = len(arr)
centers = np.arange(n)
colors = cm.RdYlBu(np.linspace(0, 1, n))
pylab.bar(centers, arr['f0'], color=colors, align='center')
ax = pylab.gca()
ax.set_xticks(centers)
ax.set_xticklabels(arr['f1'], rotation=0)
pylab.show()

bar chart


1
我相信你可以在不必处理x轴位置(sepwidthleftcenters)的情况下完成这个任务。实际上,你只需要使用 range(n) 来设置 set_xticks(),并在 bar() 中使用 align='center' 参数即可。 - Eric O. Lebigot
1
很高兴你觉得这个备注有用。这里还有一个备注:在genfromtxt()中设置dtype=None更容易:数据类型会被正确推断;此外,你还可以获得一个额外的好处,即防止水果名称超过20个字符的代码出现问题。 :) - Eric O. Lebigot
哇,我不知道 dtype=None 的行为与省略 dtype 不同。这很好知道。再次感谢。 - unutbu
是的,当我查看文档时,这也让我感到惊讶。 :) 默认值为 dtype=float(纯数值数组)。 - Eric O. Lebigot

2
正如其他人所建议的那样,Matplotlib 是你的好朋友。可以使用类似以下的代码:
import numpy as np
import matplotlib.pyplot as plt

plt.figure()
indices = np.arange(4)
width = 0.5
plt.bar(indices, [10, 3, 6, 10], width=width)
plt.xticks(indices + width/2, ('Apples', 'Oranges', 'Tomatoes', 'Pears'))
plt.show()

以下内容将帮助你入门。从文本文件中加载数据很简单。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接