import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import time
df = pd.read_csv('my_youtube_channel_csv_file.csv')
df.head()
Video | Video title | Video publish time | Subscribers lost | Subscribers gained | Views | Watch time (hours) | Average view duration | Impressions | Impressions click-through rate (%) | |
---|---|---|---|---|---|---|---|---|---|---|
0 | Total | NaN | NaN | 2366.0 | 6260.0 | 546202.0 | 29878.4798 | 0:03:16 | 3002319.0 | 9.79 |
1 | zXfFZmcgCuo | How To BUILD FAST in Fortnite Battle Royale Li... | Sep 24, 2018 | 26.0 | 525.0 | 165302.0 | 7245.2779 | 0:02:37 | 932012.0 | 12.29 |
2 | DUOYGqU31hE | Fortnite NEW PLAYGROUND MODE GAMEPLAY! NEW Pla... | Jun 26, 2018 | 23.0 | 62.0 | 2553.0 | 94.7050 | 0:02:13 | 14775.0 | 12.16 |
3 | 3Q3OAuf16Ek | Fortnite Summer Skirmish LIVE GAMEPLAY comment... | Aug 25, 2018 | 19.0 | 75.0 | 8576.0 | 491.1578 | 0:03:26 | 50329.0 | 12.06 |
4 | Ea7G2FOER9c | Fortnite Rocket COUNTDOWN Live GAMEPLAY! Fortn... | Jun 30, 2018 | 19.0 | 100.0 | 6104.0 | 327.1912 | 0:03:12 | 49676.0 | 8.50 |
This is an example of plotting a barplot using seaborn such that the data being used is filtered by views above 3000 and the user decides what type of data they want to view on the generated barplot! plt.xticks with rotation = 85 allows for the plot to have the video titles be slanted to more easily fit.
def plotBarGraph(userInput):
ax = sns.barplot(y=userInput, x='Video title', data=df.loc[df['Views'] >= 3000])
plt.xticks(rotation=85)
plt.show()
This will print a BarGraph! The user can choose between which metric you want to plot! options: Video publish time, Subscribers lost, Subscribers gained, Watch time (hours), Impressions, or lastly Impressions click-through rate (%). The user is instructed to attempt to type "Subscribers gained". Here you can see the use of plt.pause(5) which specifies that I want to pause for 5 seconds before allowing the code to continue and closing the graph.
for i in range(2):
if i==1:
print('now purposely get an error.')
userInput = input()
plotBarGraph(userInput)
plt.pause(5)
plt.close('all')
Subscribers gained
now purposely get an error.
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b309d28bd5a6> in <module> 3 print('now purposely get an error.') 4 userInput = input() ----> 5 plotBarGraph(userInput) 6 plt.pause(5) 7 plt.close('all') <ipython-input-4-7a90ce7a33ce> in plotBarGraph(userInput) 1 def plotBarGraph(userInput): ----> 2 ax = sns.barplot(y=userInput, x='Video title', data=df.loc[df['Views'] >= 3000]) 3 plt.xticks(rotation=85) 4 plt.show() /usr/local/lib/python3.8/dist-packages/seaborn/_decorators.py in inner_f(*args, **kwargs) 44 ) 45 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)}) ---> 46 return f(**kwargs) 47 return inner_f 48 /usr/local/lib/python3.8/dist-packages/seaborn/categorical.py in barplot(x, y, hue, data, order, hue_order, estimator, ci, n_boot, units, seed, orient, color, palette, saturation, errcolor, errwidth, capsize, dodge, ax, **kwargs) 3167 ): 3168 -> 3169 plotter = _BarPlotter(x, y, hue, data, order, hue_order, 3170 estimator, ci, n_boot, units, seed, 3171 orient, color, palette, saturation, /usr/local/lib/python3.8/dist-packages/seaborn/categorical.py in __init__(self, x, y, hue, data, order, hue_order, estimator, ci, n_boot, units, seed, orient, color, palette, saturation, errcolor, errwidth, capsize, dodge) 1582 errwidth, capsize, dodge): 1583 """Initialize the plotter.""" -> 1584 self.establish_variables(x, y, hue, data, orient, 1585 order, hue_order, units) 1586 self.establish_colors(color, palette, saturation) /usr/local/lib/python3.8/dist-packages/seaborn/categorical.py in establish_variables(self, x, y, hue, data, orient, order, hue_order, units) 151 if isinstance(var, str): 152 err = "Could not interpret input '{}'".format(var) --> 153 raise ValueError(err) 154 155 # Figure out the plotting orientation ValueError: Could not interpret input 'error'
Wouldn't it be nice to be able to prevent this kind of error when a user types something not allowed as input or when data that used to exist cant be read anymore such as a fif file? Error handling is the solution to this! In the next cell I provide the same def plotBarGraph(userInput) but this time adjusted to show how you can handle errors safely to prevent crashes!
def plotBarGraph(userInput):
try:
ax = sns.barplot(y=userInput, x='Video title', data=df.loc[df['Views'] >= 3000])
except:
print("Your input doesn't exist in this DataFrame so on the except clause of my def I'm going to add a special case where I tell the console where if something happens to throw an exeption that would normally crash I will throw this exception where I'm going to use Impressions as a sort of emergency last resort case to use instead of accepting the users choice and forcing a condition I know will work!")
ax = sns.barplot(y='Impressions', x='Video title', data=df.loc[df['Views'] >= 3000])
plt.xticks(rotation=85)
plt.show()
print("One more time now! options: Video publish time, Subscribers lost, Subscribers gained, Watch time (hours), Impressions, or lastly Impressions click-through rate (%). Try typing it correctly here to NOT generate an error. Try typing Subscribers gained for instance.")
print()
print("Note once the graph shows up you have 5 seconds to look at it before you should scroll down to the next textblock to type.")
for i in range(2):
if i==1:
print('now purposely get an error.')
userInput = input()
plotBarGraph(userInput)
plt.pause(5)
plt.close('all')
One more time now! options: Video publish time, Subscribers lost, Subscribers gained, Watch time (hours), Impressions, or lastly Impressions click-through rate (%). Try typing it correctly here to NOT generate an error. Try typing Subscribers gained for instance. Note once the graph shows up you have 5 seconds to look at it before you should scroll down to the next textblock to type. Subscribers gained
now purposely get an error. errorYour input doesn't exist in this DataFrame so on the except clause of my def I'm going to add a special case where I tell the console where if something happens to throw an exeption that would normally crash I will throw this exception where I'm going to use Impressions as a sort of emergency last resort case to use instead of accepting the users choice and forcing a condition I know will work!
So in summary use try when you want to have a condition be attempted where a crash is possible, and use except when you had a condition that could have resulted in a crash under certain conditions but is prevented from crashing by providing another escape route for the program to continue on without failing. Lastly as an added bonus, there is also the finally statement which is similar to how an if -elif - else statement block however regardless if the code chooses to go to either the try-except blocks, the code will always execute the finally block regardless if one or the other occured, rather than in if - elif - else statements where only one is allowed to be executed. The way to duplicate this otherwise would be to if-else if which can become clunky if needed to be repeated.