Skip to content

Instantly share code, notes, and snippets.

@hasandiwan
Last active November 13, 2019 18:40
Show Gist options
  • Save hasandiwan/391e9cc31c73b1f580992e8531ef2d89 to your computer and use it in GitHub Desktop.
Save hasandiwan/391e9cc31c73b1f580992e8531ef2d89 to your computer and use it in GitHub Desktop.
Graph a user's participated subreddits
#!.virtualenvs/data/bin/python
import argparse
import base64
from datetime import date
from collections import Counter
from io import StringIO
import os
import logging
import string
import sys
import tempfile
import matplotlib.pyplot as plt
import pandas as pd
import requests
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user', type=str)
parsed = parser.parse_args()
URL = '''https://www.reddit.com/user/{0}/overview.json'''.format(parsed.user)
user_record = requests.get(URL, params={'limit': 100}, headers={'User-Agent': "u/THVAQLJZawkw8iCKEZAE, u/cruyff8's user graph"}).json()['data']['children']
subreddit_counter = Counter()
for s in user_record:
subreddit_counter[s['data']['subreddit']] += 1
df = pd.DataFrame({'Name': subreddit_counter.keys(), 'Count': subreddit_counter.values()})
n_bins = len(subreddit_counter.keys())
x = n_bins
y = subreddit_counter.values()
fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
axs.tick_params(axis='x', rotation=90)
axs.hist(y, bins=x, density=False)
axs.set_xticklabels(subreddit_counter.keys())
plt.title("{0}'s subreddits, as of {1}".format(parsed.user, date.today().strftime('%b %d, %Y')))
output = tempfile.NamedTemporaryFile(suffix='.png')
plt.savefig(output.name)
img_data = base64.encodestring(open(output.name, 'rb').read())
resp = requests.post('https://api.imgur.com/3/image', data={'image': img_data}, headers={'Authorization': 'Client-ID e253ce5428d6eb1'})
print('Image stored on '+resp.json().get('data').get('link'))
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment