Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: plot data from a txt file

Tags:

python

How do I plot a histogram of this kind of data,

10 apples
3 oranges
6 tomatoes
10 pears

from a text file?

thanks

like image 898
Adia Avatar asked Jan 22 '23 08:01

Adia


2 Answers

Here's one way you can assign different colors to the bars. It works with even a variable number of bars.

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

like image 63
unutbu Avatar answered Jan 29 '23 10:01

unutbu


As the others suggest, Matplotlib is your friend. Something like

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()

will get you started. Loading the data from a textfile is straight forward.

like image 24
gspr Avatar answered Jan 29 '23 10:01

gspr