Python Basic Plot
Python Basic Plot
2019
Contents
Course Outcomes: You will be able to Plot graphs, curves, surfaces and contours using Python
1-1
Page 1 of 43
1-2 Lecture 1: 2D and 3D Plotting in Python
1.1.1 Setup
Run this once before the plot’s code. The individual charts, however, may redefine its own aesthetics.
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
from pylab import *
plt.style.use('seaborn-whitegrid')
sns.set_style("white")
%matplotlib inline
Topic 4 introduces you to graphing in python with Matplotlib, which is arguably the most popular graphing
and data visualization library for Python. Matplotlib is a plotting library for the Python programming
language and its numerical mathematics extension NumPy.
Matplotlib matplotlib.pyplot is a plotting library used for 2D graphics in python programming language.
It can be used in python scripts, shell, web application servers and other graphical user interface toolkits.
There are several toolkits which are available that extend python matplotlib functionality. Some of them are
separate downloads, others can be shipped with the matplotlib source code but have external dependencies.
• Basemap: It is a map plotting toolkit with various map projections, coastlines and political boundaries.
• Cartopy: It is a mapping library featuring object-oriented map projection definitions, and arbitrary
point, line, polygon and image transformation capabilities.
• Excel tools: Matplotlib provides utilities for exchanging data with Microsoft Excel.
• Natgrid: It is an interface to the natgrid library for irregular gridding of the spaced data.
Page 2 of 43
Lecture 1: 2D and 3D Plotting in Python 1-3
Scikit-learn requires:
1.2.2 Histogram
Page 3 of 43
1-4 Lecture 1: 2D and 3D Plotting in Python
Bins
1.2.2.1 2D Histogram
The barh() function length of the bar represents the magnitude of the values
Page 4 of 43
Lecture 1: 2D and 3D Plotting in Python 1-5
Exploding a wedge
• When a wedge is too small that make difficulties to display the percentage inside of it
• Small wedges can be seen easily if they are offset from the rest of the pie
• The explode=keyword argument is a list of values, one for wedge the s instruct matplotlib how much
to offset the wedges, as a fraction of the radius
•
1.2.5 Scatter
To use shuffle, import the Python random package by adding the line import random near the top of your
program. Then, if you have a list called x, you can call random.shuffle(x) to have the random shuffle function
reorder the list in a randomized way.
3D Plotting in Python
Page 5 of 43
1.2.1. Line Chart
November 2, 2019
data= np.random.randint(0,20,size=10)
data
[64]: array([19, 14, 14, 7, 8, 8, 11, 18, 13, 15])
[65]: plt.plot(data);
plt.plot(data*3);
plt.title('My first graph!')
[65]: Text(0.5, 1.0, 'My first graph!')
Page 6 of 43
[66]: # Plotting a line
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
Page 7 of 43
[67]: #Plotting two or more lines on same plot
# line 1 points
x1 = [1,2,3]
y1 = [2,4,1]
# plotting the line 1 points
plt.plot(x1, y1, label = "line 1")
# line 2 points
x2 = [1,2,3]
y2 = [4,1,3]
# plotting the line 2 points
plt.plot(x2, y2, label = "line 2")
Page 8 of 43
# function to show the plot
plt.show()
"""
Here, we plot two lines on same graph. We differentiate
between them by giving them a name(label) which is passed
as an argument of .plot() function. The small rectangular
box giving information about type of line and its color
is called legend. We can add a legend to our plot using
.legend() function.
"""
# x axis values
x = [1,2,3,4,5,6]
# corresponding y axis values
y = [2,4,1,5,2,6]
Page 9 of 43
# plotting the points
plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3)
# setting x and y axis range
plt.ylim(1,8)
plt.xlim(1,8)
Page 10 of 43
[68]: 'As you can see, we have done several customizations like:\n1. setting the line-
width, line-style, line-color.\n2. setting the marker, markers face color,
markers size.\n3. overriding the x and y axis range. If overriding is not \n
done, pyplot module uses auto-scale feature to set the axis range\n and
scale.\n'
[69]: # Plotting curves of given equation
Page 11 of 43
[69]: '\nHere, we use NumPy which is a general-purpose array-processing\n package in
python.\n1. To set the x axis values, we use np.arange() method in \n which
rst two arguments are for range and third one for\n2. step-wise increment. The
result is a numpy array.\n3. To get corresponding y-axis values, we simply use
predened\n np.sin() method on the numpy array.\n4. Finally, we plot the points
by passing x and y arrays to \n the plt.plot() function.\n'
[70]: import helper
precip_2018=helper.precip_sums_for_year()
precip_2018
[70]: [(1, 3.92),
(2, 1.7000000000000002),
(3, 4.799999999999999),
(4, 5.35),
(5, 5.12),
(6, 1.9799999999999998),
(7, 4.92),
(8, 6.619999999999999),
(9, 7.970000000000001),
(10, 4.579999999999999),
(11, 7.1),
(12, 6.230000000000001)]
[71]: precip_2018=[month[1] for month in precip_2018]
precip_2018
Page 12 of 43
[71]: [3.92,
1.7000000000000002,
4.799999999999999,
5.35,
5.12,
1.9799999999999998,
4.92,
6.619999999999999,
7.970000000000001,
4.579999999999999,
7.1,
6.230000000000001]
[72]: plt.plot(precip_2018);
plt.xticks(ticks=np.arange(len(precip_2018)), labels=helper.MONTHS);
[73]: helper.MONTHS
[73]: array(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'], dtype='<U3')
[74]: plt.plot(precip_2018);
plt.xticks(ticks=np.array([1,2,8,10]) , labels=helper.MONTHS);
Page 13 of 43
[75]: low_precip = np.argmin(precip_2018)
high_precip = np.argmax(precip_2018)
[76]: plt.plot(precip_2018)
plt.xticks( ticks=np.array([low_precip,high_precip]),
labels=helper.MONTHS[[low_precip,high_precip]]);
Page 14 of 43
[77]: plt.plot(precip_2018)
plt.xticks( ticks=np.array([high_precip]),
labels=np.array([helper.MONTHS[high_precip]]));
[78]: plt.plot(precip_2018)
plt.xticks( ticks=[]);
10
Page 15 of 43
[79]: import math
lower=math.floor(precip_2018[low_precip])
upper=math.ceil(precip_2018[high_precip])
precip_ticks=np.arange(lower,upper,0.5)
plt.plot(precip_2018);
plt.xticks(ticks=np.arange(len(precip_2018)), labels=helper.MONTHS);
plt.yticks(ticks=precip_ticks);
11
Page 16 of 43
1.2.2. Histogram
November 2, 2019
# plotting a histogram
plt.hist(ages, bins, range, color = 'green',
histtype = 'bar', rwidth = 0.8)
# x-axis label
plt.xlabel('age')
# frequency label
plt.ylabel('No. of people')
# plot title
plt.title('My histogram')
Page 17 of 43
[2]: ' Here, we use plt.hist() function to plot a histogram.\n frequencies are passed
as the ages list.\n Range could be set by dening a tuple containing min and max
value.\n Next step is to bin the range of valuesthat is, divide the \n entire
range of values into a series of intervalsand then\n count how many values fall
into each interval. Here we have\n dened bins = 10. So, there are a total of
100/10 = 10 intervals.\n'
[3]: helper.weather[0].keys()
[3]: dict_keys(['fogground', 'snowfall', 'dust', 'snowdepth', 'mist', 'drizzle',
'hail', 'fastest2minwindspeed', 'thunder', 'glaze', 'snow', 'ice', 'fog',
'temperaturemin', 'fastest5secwindspeed', 'freezingfog', 'temperaturemax',
'blowingsnow', 'freezingrain', 'rain', 'highwind', 'date', 'precipitation',
'fogheavy', 'smokehaze', 'avgwindspeed', 'fastest2minwinddir',
'fastest5secwinddir'])
[4]: jan_temps=helper.monthly_data_by_key(month=1, key='temperaturemax')
[5]: len(jan_temps)
[5]: 372
[6]: y,x,_ = plt.hist(jan_temps);
Page 18 of 43
[7]: plt.plot(x[:-1],y);
Page 19 of 43
[9]: data=np.random.randn(10000)
plt.hist(data, bins=25, color='tomato');
Page 20 of 43
[10]: data=np.random.uniform(size=1000)
plt.hist(data, bins=100);
Page 21 of 43
1.2.3. Bar Charts
November 2, 2019
# heights of bars
height = [10, 24, 36, 40, 5]
Page 22 of 43
[2]: ' Here, we use plt.bar() function to plot a bar chart.\nx-coordinates of left
side of bars are passed along with heights of bars.\nyou can also give some name
to x-axis coordinates by dening tick_labels\n'
[3]: import helper
precip_sums_2018=helper.precip_sums_for_year()
plt.bar(np.arange(len(helper.MONTHS)),[month[1] for month in precip_sums_2018]);
plt.xticks(ticks=np.arange(len(helper.MONTHS)),labels=helper.MONTHS);
[3]: '\n'
Page 23 of 43
[4]: #Horizontal
plt.barh(np.arange(len(helper.MONTHS)),[month[1] for month in␣
,→precip_sums_2018]);
plt.yticks(ticks=np.arange(len(helper.MONTHS)),labels=helper.MONTHS);
Page 24 of 43
[5]: #Stacked
import numpy as np
import matplotlib.pyplot as plt
import helper
precip_sums_2018=helper.precip_sums_for_year(year=2018)
precip_sums_2017=helper.precip_sums_for_year(year=2017)
precip_sums_2016=helper.precip_sums_for_year(year=2016)
plt.bar(np.arange(len(helper.MONTHS)),value_2018, label='2018')
plt.legend()
plt.bar(np.arange(len(helper.MONTHS)),value_2017,
bottom=value_2018,label='2017')
plt.legend()
plt.bar(np.arange(len(helper.MONTHS)),value_2016,
bottom=value_2017+value_2018,label='2016')
plt.legend()
plt.xticks(ticks=np.arange(len(helper.MONTHS)),labels=helper.MONTHS);
Page 25 of 43
precip_sums_2018=helper.precip_sums_for_year(year=2018)
precip_sums_2017=helper.precip_sums_for_year(year=2017)
precip_sums_2016=helper.precip_sums_for_year(year=2016)
plt.barh(np.arange(len(helper.MONTHS)),value_2018, label='2018')
plt.legend()
plt.barh(np.arange(len(helper.MONTHS)),value_2017,
left=value_2018,label='2017')
plt.legend()
plt.barh(np.arange(len(helper.MONTHS)),value_2016,
left=value_2017+value_2018,label='2016')
plt.legend()
plt.yticks(ticks=np.arange(len(helper.MONTHS)),labels=helper.MONTHS);
[7]: #Grouped
import numpy as np
import matplotlib.pyplot as plt
import helper
precip_sums=[helper.precip_sums_for_year(),helper.precip_sums_for_year(
year=2017), helper.precip_sums_for_year(year=2016)]
years=range(2016,2019)
data=dict(zip(years,precip_sums))
Page 26 of 43
for key in data.keys():
data[key] = [month[1] for month in data[key]]
group_width = 0.7
offsets=[-group_width/3 , 0, group_width/3]
for index, key in enumerate(sorted(data.keys())):
plt.bar(np.arange(len(data[key]))-offsets[index],data[key],
width=group_width/3, label= str(key))
plt.xticks(ticks=np.arange(len(helper.MONTHS)),labels=helper.MONTHS);
plt.legend()
Page 27 of 43
7
Page 28 of 43
1.2.4. Pie Chart
November 2, 2019
Page 29 of 43
[26]:
# defining labels
activities = ['eat', 'sleep', 'work', 'play']
# plotting legend
plt.legend()
Page 30 of 43
4. Color for each label is dened using a list called colors.
5. shadow = True will show a shadow beneath each label in pie-char t.
6. startangle rotates the start of the pie chart by given degrees
counterclockwise from the x-axis.
7. explode is used to set the fraction of radius with which we offset
each wedge.
"""
[26]: '\n1. Here, we plot a pie chart by using plt.pie() method.\n2. First of all, we
dene the labels using a list called activities.\n3. Then, portion of each label
can be dened using another list\n called slices.\n4. Color for each label is
dened using a list called colors.\n5. shadow = True will show a shadow beneath
each label in pie-char t.\n6. startangle rotates the start of the pie chart by
given degrees \n counterclockwise from the x-axis.\n7. explode is used to set
the fraction of radius with which we offset\n each wedge.\n'
[27]: import helper
precip_2018 = helper.precip_sums_for_year()
totals=[month[1] for month in precip_2018]
plt.pie(totals, labels=helper.MONTHS);
Page 31 of 43
[28]: plt.pie(totals, labels=helper.MONTHS, startangle=90,
labeldistance=1.1, rotatelabels=True);
Page 32 of 43
[30]: precip_2018=helper.precip_sums_for_year(year=2015)
precip_2017=helper.precip_sums_for_year(year=2017)
precip_2016=helper.precip_sums_for_year(year=2016)
precip_2015=helper.precip_sums_for_year(year=2015)
Page 33 of 43
[31]: _,years,pcts=plt.pie(sep_precip, autopct='%.2f%%', labels=labels);
years[0].set_fontweight('bold')
pcts[1].set_fontstyle('italic')
[32]: explosions=np.zeros(12)
min_position=np.argmin(totals)
explosions[min_position]=0.4
plt.pie(totals,autopct='%.2f%%', labels=helper.MONTHS,
explode=explosions);
Page 34 of 43
[33]: import numpy as np
import matplotlib.pyplot as plt
import helper
precip_2018=helper.precip_sums_for_year()
totals=[month[1] for month in precip_2018]
explosions=np.zeros(12)
min_position=np.argmin(totals)
explosions[min_position]=0.4
explosions[np.argmax(totals)]=0.6
plt.pie(totals,autopct='%.2f%%', labels=helper.MONTHS,
explode=explosions);
Page 35 of 43
8
Page 36 of 43
1.2.5. Scatter Plots
November 2, 2019
# x-axis label
plt.xlabel('x - axis')
# frequency label
plt.ylabel('y - axis')
# plot title
plt.title('My scatter plot!')
# showing legend
plt.legend()
Page 37 of 43
[2]: ' \n1. Here, we use plt.scatter() function to plot a scatter plot.\n2. Like a
line, we dene x and corresponding y axis values here as well.\n3. marker
argument is used to set the character to use as marker. Its size\n can be dened
using s parameter. \n'
[3]: # helper.py
max_temps=helper.monthly_data_by_key(month=1, key='temperaturemax')
min_temps=helper.monthly_data_by_key(month=1, key='temperaturemin')
[4]: plt.scatter(max_temps,min_temps); #scatter for finding any relationships
Page 38 of 43
[5]: avg_wind=helper.monthly_data_by_key(month=1, key="avgwindspeed")
fast_wind=helper.monthly_data_by_key(month=1, key="fastest5secwindspeed")
[6]: plt.scatter(avg_wind, fast_wind, color='tomato');
Page 39 of 43
[7]: points =helper.get_wind_points()
[8]: plt.scatter(points[:,0], points[:,1]);
Page 40 of 43
[10]: from sklearn.datasets import make_blobs
data=make_blobs()
points=data[0]
x,y=points[:,0],points[:,1]
plt.plot(x,y);
[11]: plt.scatter(x,y);
Page 41 of 43
[12]: np.random.shuffle(points)
plt.scatter(points[:,0],points[:,1]);
[13]: data=make_blobs()
points=data[0]
plt.scatter(points[:,0],points[:,1], c=data[1]);
Page 42 of 43
[14]: data=helper.get_blobs()
points=data[0]
x,y=points[:,0],points[:,1]
plt.scatter(x,y,c=data[1]);
Page 43 of 43