2

I have a text file with a username and the app they used for posting a tweet in this format. This is a small sample from the file.

John, Twitter for iPhone
Doe, web
Jack, Twitter for Android
foo, Twitter for iPhone
bar, Twitter for iPhone
foo1, TweetDeck
John1, Twitter for iPhone
Doe2, web
Jack3, Twitter for Android
foo2, Twitter for iPhone
bar2, Twitter for iPhone
foo3, Tweet Button
a1,Twitter for iPhone
a2,web
s1,Mobile Web
s2,Twitter for iPhone
s3,Twitterrific

How do I plot the app information as a bar chart or a pie chart? I don't care about the username. Just a chart that compares the different apps. Which charting library is well suited for simple plots like this?

4 Answers 4

3

Here's some sample code to get you started with a pie chart in Matplotlib. I'm assuming you've saved your data to a file called data.txt.

import matplotlib.pyplot as plt

apps = {}

with open('data.txt', 'r') as f:
    lines = f.readlines()

for line in lines:
    app = line.split(',')[1].strip()
    if app not in apps:
        apps[app] = 1
    else:
        apps[app] += 1

data = [(k,apps[k]) for k in apps]
data_s = sorted(data, key=lambda x: x[1])

x = [app[1] for app in data_s]
l = [app[0] for app in data_s]
plt.pie(x)
plt.legend(l, loc='best')

plt.show()
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. Just want to add, Python (collections.Counter) can handle the counting and sorting data_s = collections.Counter([line.split(',')[1].strip() for line in f.readlines()]).most_common()
0

I used pygooglechart. It's simple, intuitive and has great examples.

Check this out first.

Comments

0

Matplotlib is a popular option, and it has good examples.

I've personally made use of PyX, and I've found that it can be simpler for certain types of charts moreso than others.

Comments

0

I reused @Brandan's code and (will all respect) improved it by introducing collections.Counter

import matplotlib.pyplot as plt
import collections

with open('data.txt', 'r') as f:
    data_s = collections.Counter([line.split(',')[1].strip() for line in f.readlines()]).most_common()


x = [app[1] for app in data_s]
l = [app[0] for app in data_s]
plt.pie(x)
plt.legend(l, loc='best')

plt.show()

Comments

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.