Feel free to read the code on GitHub
In [1]:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import numpy as np
# Import Data
df = pd.read_csv('c:/2/gdppercap.txt')
df
Out[1]:
To make vector of data: series 1, series 2 and labels
In [2]:
lebel = df.continent.to_list()
lebel
Out[2]:
In [3]:
series1=np.round(df['1952'].to_list(), decimals=1)
series1
Out[3]:
In [4]:
series2=np.round(df['1957'].to_list(), decimals=1)
series2
Out[4]:
Needed parameters
In [5]:
lebel = df.continent.to_list()
series1=np.round(df['1952'].to_list(), decimals=1)
series2=np.round(df['1957'].to_list(), decimals=1)
title = 'Slopechart: Comparing GDP Per Capita between 1952 vs 1957'
ylabel ='Mean GDP Per Capita'
xlabel =["1952", "1957"]
Definition of the trigger
In [6]:
def SlopeChart(series1, series2, title, xlabel, ylabel, lebel):
# Labels formatting
left_label = [str(c) + ', '+ str(round(y)) for c, y in zip(lebel, series1)]
right_label = [str(c) + ', '+ str(round(y)) for c, y in zip(lebel, series2)]
klass = ['red' if (y1-y2) < 0 else 'green' for y1, y2 in zip(series1, series2)]
# lines color
def newline(p1, p2, color='black'):
ax = plt.gca()
l = mlines.Line2D([p1[0],p2[0]], [p1[1],p2[1]], color='red' if p1[1]-p2[1] > 0 else 'green', marker='o', markersize=6)
ax.add_line(l)
return l
fig, ax = plt.subplots(1,1,figsize=(14,14), dpi= 380)
# Vertical Lines
ax.vlines(x=1, ymin=500, ymax=13000, color='black', alpha=0.7, linewidth=1, linestyles='dotted')
ax.vlines(x=3, ymin=500, ymax=13000, color='black', alpha=0.7, linewidth=1, linestyles='dotted')
# Points
ax.scatter(y=series1, x=np.repeat(1, df.shape[0]), s=10, color='black', alpha=0.7)
ax.scatter(y=series2, x=np.repeat(3, df.shape[0]), s=10, color='black', alpha=0.7)
# Line Segmentsand Annotation
for p1, p2, c in zip(series1, series2, df['continent']):
newline([1,p1], [3,p2])
ax.text(1-0.05, p1, c + ', ' + str(round(p1)), horizontalalignment='right', verticalalignment='center', fontdict={'size':14})
ax.text(3+0.05, p2, c + ', ' + str(round(p2)), horizontalalignment='left', verticalalignment='center', fontdict={'size':14})
# 'Before' and 'After' Annotations
ax.text(1-0.05, 13000, 'BEFORE', horizontalalignment='right', verticalalignment='center', fontdict={'size':18, 'weight':700})
ax.text(3+0.05, 13000, 'AFTER', horizontalalignment='left', verticalalignment='center', fontdict={'size':18, 'weight':700})
# Decoration
ax.set_title(title, fontdict={'size':22})
ax.set(xlim=(0,4), ylim=(0,14000), ylabel=ylabel)
ax.set_xticks([1,3])
ax.set_xticklabels(xlabel)
plt.yticks(np.arange(500, 13000, 2000), fontsize=12)
# Lighten borders
plt.gca().spines["top"].set_alpha(.0)
plt.gca().spines["bottom"].set_alpha(.0)
plt.gca().spines["right"].set_alpha(.0)
plt.gca().spines["left"].set_alpha(.0)
plt.show()
In [7]:
SlopeChart(series1, series2, title, xlabel, ylabel, lebel)
In [8]:
df2 = pd.read_csv('c:/1/WorldHappinessReport.csv')
df2.head(5)
Out[8]:
In [9]:
kot = df2.pivot_table(index='Region',columns=['Year'], values='Happiness Rank', aggfunc='mean')
kot
Out[9]:
In [10]:
PKP = kot.reset_index()
labelPKP = PKP['Region'].to_list()
labelPKP
Out[10]:
In [11]:
PKP.columns
Out[11]:
In [12]:
PKP.columns = ['Region', '2015', '2016', '2017']
In [13]:
series1 = np.round(PKP['2015'].to_list(), decimals=1)
series1
Out[13]:
In [14]:
series2 = np.round(PKP['2017'].to_list(), decimals=1)
series2
Out[14]:
In [15]:
def SlopeChart(series1, series2, title, xlabel, ylabel, lebelPKP):
# Labels formatting
left_label = [str(c) + ', '+ str(round(y)) for c, y in zip(labelPKP, series1)]
right_label = [str(c) + ', '+ str(round(y)) for c, y in zip(labelPKP, series2)]
klass = ['red' if (y1-y2) < 0 else 'green' for y1, y2 in zip(series1, series2)]
# lines color
def newline(p1, p2, color='black'):
ax = plt.gca()
l = mlines.Line2D([p1[0],p2[0]], [p1[1],p2[1]], color='red' if p1[1]-p2[1] > 0 else 'green', marker='o', markersize=6)
ax.add_line(l)
return l
fig, ax = plt.subplots(1,1,figsize=(14,14), dpi= 380)
# Vertical Lines
ax.vlines(x=1, ymin=0, ymax=120, color='black', alpha=0.7, linewidth=1, linestyles='dotted')
ax.vlines(x=3, ymin=0, ymax=120, color='black', alpha=0.7, linewidth=1, linestyles='dotted')
# Points
ax.scatter(y=series1, x=np.repeat(1, PKP.shape[0]), s=10, color='black', alpha=0.7)
ax.scatter(y=series2, x=np.repeat(3, PKP.shape[0]), s=10, color='black', alpha=0.7)
# Line Segmentsand Annotation
for p1, p2, c in zip(series1, series2, labelPKP):
newline([1,p1], [3,p2])
ax.text(1-0.05, p1, c + ', ' + str(round(p1)), horizontalalignment='right', verticalalignment='center', fontdict={'size':14})
ax.text(3+0.05, p2, c + ', ' + str(round(p2)), horizontalalignment='left', verticalalignment='center', fontdict={'size':14})
# 'Before' and 'After' Annotations
ax.text(1-0.05, 140, 'BEFORE', horizontalalignment='right', verticalalignment='center', fontdict={'size':18, 'weight':700})
ax.text(3+0.05, 140, 'AFTER', horizontalalignment='left', verticalalignment='center', fontdict={'size':18, 'weight':700})
# Decoration
ax.set_title(title, fontdict={'size':22})
ax.set(xlim=(0,4), ylim=(0,150), ylabel=ylabel) ## Skala osi Y
ax.set_xticks([1,3])
ax.set_xticklabels(xlabel)
plt.yticks(np.arange(20, 150, 40), fontsize=12) ## Podziałaka osi Y
# Lighten borders
plt.gca().spines["top"].set_alpha(.0)
plt.gca().spines["bottom"].set_alpha(.0)
plt.gca().spines["right"].set_alpha(.0)
plt.gca().spines["left"].set_alpha(.0)
plt.show()
In [16]:
labelPKP
series1
series2
title = 'Changing the the level of happiness: 2015 vs. 2017'
ylabel ='Less points - more happiness'
xlabel =["2015", "2017"]
In [17]:
SlopeChart(series1, series2, title, xlabel, ylabel, labelPKP)
Source IPYNB file


