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?

Nathan Musoke
  • 166
  • 1
  • 12
Ram
  • 51
  • 2
  • 6

4 Answers4

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()
Brendan Wood
  • 6,220
  • 3
  • 30
  • 28
  • 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()` – bpgergo May 30 '12 at 17:32
0

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

Check this out first.

Community
  • 1
  • 1
nullpotent
  • 9,162
  • 1
  • 31
  • 42
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.

Makoto
  • 104,088
  • 27
  • 192
  • 230
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()
bpgergo
  • 15,669
  • 5
  • 44
  • 68