0

I am trying to plot a pie chart from a .txt file with data-set looks like:

asp: 2.11
glu: 1.11
arg: 0.99
his: 5.11
acid: 11.1
base: 2.11

now, 1) I want to plot a pie chart with first 4 entries, with proper labeling.
2) and then another pie plot using last 2 entries.

I was trying with this following code but I am getting errors. My code is:

from pylab import *
inp = open('c:/users/rox/desktop/xx.txt','r').read().strip().replace(': ',' ').split('\n')
for line in map(str.split,inp):
    x = line[0]
    z = line[1]
    fracs = [x]
    labels = [z]
    pie(fracs,labels=labels,explode=None,autopct='%1.1f%%,shadow=False)
    show()

but this code is generating an error report: Could not convert string to float...

and do I need to use tempfile to plot first 4 entries present in the .txt file.

if I want to plot pie chart using last two line of data set, then could it be done using slicing.

0

1 Answer 1

3

Edit: make input more general, so multiple plots can be read from same file:

import matplotlib.pyplot as plt

def read_data(f, num_lines=1, split_on=':'):
    lines = (f.next() for i in range(num_lines))
    pieces = (line.split(split_on) for line in lines)
    data = ((a,float(b)) for a,b in pieces)
    return zip(*data)

with open("xx.txt") as inf:
    amino_names, amino_values = read_data(inf, 4)
    ph_names, ph_values = read_data(inf, 2)

fig = plt.figure(figsize=(2,1))
p1 = fig.add_subplot(1,2,1)
p1.pie(amino_values, labels=amino_names)
p2 = fig.add_subplot(1,2,2)
p2.pie(ph_values, labels=ph_names)
fig.show()

results in

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

problem in last line. It raises error : 'tuple' object has no attribute 'show'. and could be corrected if use: plt.show() in next line.
@Ovisek: which version Python, matplotlib, OS? Works for me as-is with Windows 7 64-bit, Python 2.7.2, matplotlib 1.1.0
okey it's fine but for plotting pie with last 2 entries how do i skip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.