Introduction to Computational Thinking More Visualization
CT @ VT Why Functions How can code be made available for others to use? Cut/paste of code (as we did for Blockly Python) works only for small amounts of code Need better ways to organize and reuse large amounts of code Python provides three ways Function – code that performs a single action Simple action: round a number Complex action: generate a visualization Module – a collection of related functions e.g., all of visualization functions Package – a collection of related modules e.g., all of the modules that do different forms of visualization Fall 201 2015 Slide 2
CT @ VT Packages and Modules Matplotlib: commonly used in Python to create visualizations (see http://matplotlib.org/gallery.html). Syntax: matplotlib.pyplot.show() Shorthand: import matplotlib.pyplot as plt ... plt.show() matplotlib module package pyplot show functions plot Fall 201 2015 Slide 3
CT @ VT Functions in 3 easy steps Step 1: functions have names show() # show the visualization Step 2: functions may have parameters plot(data) # plot the list data Step 3: functions may return a value val = sqrt(number) # square root Notes The user documentation tells you what a function does and what you need to use it You do not need to know how a function is implemented to use it (and you often don’t care) Reusing functions is a highly valued professional practice Fall 201 2015 Slide 4
CT @ VT Three simple visualizations Name Function Typical Usage Name Change or variation (sometimes Line plot plot(x) over time) Scatter plot scatter(x,y) Relation between x and y Histogram hist(x) Distribution over categories of x (aka Bar Chart) Simple statistical measures: mean (average) range (min-max) median (middle value) More complex statistical measures: regressions ….. Fall 201 2015 Slide 5
CT @ VT Line plot visualizations Question: What is the variation in earthquake intensity? import earthquakes # get all the reports of earthquakes of the current day quakes = earthquakes.get_report('day', 'all') quake_list = quakes[“earthquakes”] #create an empty list significance_list = [] for quake in quakes_list: # add the significance of the next earthquake to the list significance_list.append(quake["significance"]) plt.plot(significance_list) plt.show() Click to save Fall 201 2015 Slide 6
CT @ VT Scatter plot visualization Question: What is the relationship between the depth and magnitude of earthquakes? import earthquakes import matplotlib.pyplot as plt … depths = [ … ] magnitudes = […] … plt.scatter(depths, magnitudes) plt.show() Fall 201 2015 Slide 7
CT @ VT Histogram visualization Question: What is the distribution of the magnitudes of earthquakes? import earthquakes import matplotlib.pyplot as plt … magnitudes = [ … ] … plt.hist(magnitudes) plt.show() Fall 201 2015 Slide 8
CT @ VT Next Steps Work as usual to complete the classwork for today Homework gives you more practice with these ideas Fall 201 2015 Slide 9
Recommend
More recommend