Created
February 21, 2017 11:35
-
-
Save n-kb/69c3da73282f01c7d51723ca589e7c61 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import csv | |
import urllib2 | |
import numpy as np | |
import matplotlib.pyplot as plt | |
import matplotlib.image as image | |
import pylab | |
from PIL import Image | |
DATA_URL = "https://docs.google.com/spreadsheets/d/19infjiXqudq86oL8XT-1SEtP1-QrRMrBXKfimrVPSl8/pub?gid=0&single=true&output=csv" | |
START_YEAR = 1600 | |
END_YEAR = 2017 | |
response = urllib2.urlopen(DATA_URL) | |
cr = csv.reader(response) | |
next(cr) # Skips first line | |
wars = [] # Will contain all data | |
for row in cr: | |
wars.append({"start": int(row[1]), "end": int(row[2]), "casualties": int(row[3]), "duration": int(row[2]) - int(row[1])}) | |
# Loops through all years | |
years = [] # For intensity | |
years_bool = [] # For plotting | |
for year in range(0, END_YEAR - START_YEAR): | |
year_actual = year + START_YEAR | |
years.append(0) # init the year | |
years_bool.append(0) | |
# Loops through the wars and get avg casualties per year | |
for war in wars: | |
if war["start"] <= year_actual and war["end"] >= year_actual: | |
years_bool[year] = 1 | |
years[year] += (war["casualties"] / war["duration"]) | |
# Makes the graph | |
figure = plt.figure(1, figsize=(10, 5)) | |
ax = plt.subplot(111) | |
bars = ax.bar(range(0, END_YEAR - START_YEAR), years_bool, 1, linewidth = 0) | |
year = 0 | |
for bar in bars: | |
opacity = 0 | |
opacity = round(years[year] / 1e4) / 100 | |
year_actual = year + START_YEAR | |
if opacity > 1: | |
opacity = 1 | |
bar.set_color((0,0,0,opacity)) # Sets intensity, max opacity for 1m casualties per year | |
# Special case for 1957 | |
if year_actual == 1957: | |
bar.set_color('#0D4F8B') | |
print year_actual, years[year], opacity, bar.get_facecolor() | |
year += 1 | |
# Set ticks to actual years | |
ticks = np.arange(0, END_YEAR - START_YEAR, 100) | |
labels = np.arange(START_YEAR, END_YEAR, 100) | |
plt.xticks(ticks, labels) | |
ax.set_ylim([0,1]) | |
# Removes everything, makes thick frame | |
ax.spines['right'].set_linewidth(5) | |
ax.spines['top'].set_linewidth(5) | |
ax.spines['bottom'].set_linewidth(5) | |
ax.spines['left'].set_linewidth(5) | |
plt.tick_params( | |
axis='both', | |
which='both', | |
bottom='off', | |
top='off', | |
left= 'off', | |
right='off', | |
labelleft='off') | |
# Makes layout more legible | |
figure.tight_layout() | |
# Saves image | |
pylab.savefig('graph.png',dpi=80) | |
plt.close(figure) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment