0% found this document useful (0 votes)
82 views

Python Basic Plot

The document discusses plotting in Python. It covers: - Types of visualizations like line charts, histograms, bar charts, pie charts, and scatter plots - How to create basic line charts, histograms, grouped and stacked bar charts using Matplotlib - Additional chart types like 2D histograms, horizontal bar charts, and exploding wedges in pie charts - Customizing visualizations and an introduction to 3D plotting
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Python Basic Plot

The document discusses plotting in Python. It covers: - Types of visualizations like line charts, histograms, bar charts, pie charts, and scatter plots - How to create basic line charts, histograms, grouped and stacked bar charts using Matplotlib - Additional chart types like 2D histograms, horizontal bar charts, and exploding wedges in pie charts - Customizing visualizations and an introduction to 3D plotting
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

UECM1703-Introduction to Scientific Computing Oct.

2019

Lecture 1: 2D and 3D Plotting in Python


Lecturer: Dr. Leyla Ranjbari Contact: [email protected]

Topic 4: Graphics - Teaching Plan


4.1 2-D plots
4.2 Plotting a set of data, Plotting a function, Plotting parametric curves
4.3 Line styles, markers and colours, Labels, title, legends, Axis control
4.4 Overlay plots and subplots, Specialized 2-D plots
4.5 3-D plots
4.6 Curve plot, contour, surface, mesh
4.7 Colour bar and colour shading
4.8 Plotting vector fields
Lab 6: 2D plotting functions
Lab 7: 3D plotting functions
Test 2 (CO2, 15%) 14 Nov 2019 [Total : 20 marks]
Table 1.1: Details - Topic 4: Graphics [Course Learning Outcomes (CO2)]

Contents

1.1 Get Started 1-2


1.1.1 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

1.2 Types of visualizations 1-3


1.2.1 Line Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
1.2.2 Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
1.2.2.1 2D Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
1.2.3 Bar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
1.2.3.1 Grouped Bar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
1.2.3.2 Horizontal Bar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
1.2.3.3 Stacked Bar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
1.2.4 Pie Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
1.2.5 Scatter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5

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 Get Started

• Be familiar with Python 3

• Be familiar with Numpy and pandas packages

• Be familiar with Jupyter Notebook: Installation in cmd: jupyter notebook

• Anaconda is not required. Matplotlib depends on Python.Go to Anaconda Distribution

1.1.1 Setup

Run this once before the plot’s code. The individual charts, however, may redefine its own aesthetics.

# installing matplotlib in command window: pip install matplotlib


# installing brewer2mpl in command window: pip install brewer2mpl
# installing seaborn in command window: pip install seaborn
# seaborn is a library used for data visualization

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.

• Mplot3d: It is used for 3-D plots.

• 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

1.2 Types of visualizations

1.2.1 Line Chart

• Rendered with the plot() function


• Accept at leats a single iterable
• values plotted along the y-axis
• Most of the time this course will use a list or numpy ndarray
• x-axis vaues default to consecutive integers, starting with 0

Matplotlib will infer positions of the ticks.

• Get more control with the xticks() function


• Take two iterables:
– Locations of the ticks
– Values associated with the tickes

Both explicit x and y values are passed with two iterables:


Installing scikit-learn:

• pip install -U scikit-learn


• or conda: conda install scikit-learn

Scikit-learn requires:

• Python (>= 3.5)


• NumPy (>= 1.11.0)
• SciPy (>= 0.17.0)
• joblib (>= 0.11)

1.2.2 Histogram

• Visualize frequency distribution


• Generated with the hist() function
– Accept a dataset
– Divides the dataset into evenly spaced intervals
– Matches each value in the dataset with an interval
– Counts the number of values in each interval

Page 3 of 43
1-4 Lecture 1: 2D and 3D Plotting in Python

Bins

• By increasing the number of intervals, we can see more detail


• The intervals are called ”bins”.
• bins=keyword argument
• Default=10

1.2.2.1 2D Histogram

• Generated with the hist2d() function


• Creats a histogram for each of two datasets
– One becomes the x-axis, other becomes the y-axis
– The perspective is top down.
– Darker color shows higher values (intensity is shown by colors)
– Counts the number of values in each interval

1.2.3 Bar Chart

• Also called a column chart


• Similar to a line chart (y-axes represents the values)
• Represents individual values with bars
• Taller bars represent greater values
• A bar chart is not a histogram and vice versa.
• The bar(0) function Accept two iterables: x-coordinates of the bars and ’heights’

1.2.3.1 Grouped Bar Chart

1.2.3.2 Horizontal Bar Chart

The barh() function length of the bar represents the magnitude of the values

1.2.3.3 Stacked Bar Chart

1.2.4 Pie Chart

• Like the stacked bar chart, represents parts of a whole


• Display only a single dataset
• values are percentages

Page 4 of 43
Lecture 1: 2D and 3D Plotting in Python 1-5

• will always add up to 100


• The entire datasets is represented as a circle.
• Th values are wedges.
• The size of each wedge is proportional to the total of the values. Each wedge (or value) is represented
by a slice of the pie (or dataset)
• plt.pie() function: first wedge in the right top side of the part and display the remaining wedges moving
counter clockwise

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

• Displays individual points


• Order is not significant
• Scatter plots show relationships between the points
• the scatter() function
• Accept two iterable:
– First is the x-axis
– Second is the y-axis

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.

How to customize visualizations

3D Plotting in Python

Creating Advanced Visualization with Matplotlib

Interactive and animated visualizations

Page 5 of 43
1.2.1. Line Chart

November 2, 2019

[63]: # importing the required module


import numpy as np
""" The numpy package (module) is used in almost all numerical
computation using Python. It is a package that provide
high-performance vector, matrix and higher-dimensional
data structures for Python. It is implemented in C and
Fortran so when calculations are vectorized (formulated
with vectors and matrices), performance is very good.
"""
import matplotlib.pyplot as plt
[64]: # numpy.random.randint(low, high=None, size=None, dtype='l')
# Return random integers from low (inclusive) to high (exclusive)

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]

# plotting the points


plt.plot(x, y)

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph


plt.title('My Second graph!')

# function to show the plot


plt.show()

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")

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('Two lines on same graph!')

# show a legend on the plot


plt.legend()

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.
"""

[67]: '\nHere, we plot two lines on same graph. We differentiate\nbetween them by


giving them a name(label) which is passed\nas an argument of .plot() function.
The small rectangular \nbox giving information about type of line and its color
\nis called legend. We can add a legend to our plot using \n .legend()
function.\n'
[68]: # Customization of Plots
# Here, we discuss some elementary customizations applicable on almost any plot.

# 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)

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph


plt.title('Some cool customizations!')

# function to show the plot


plt.show()
"""As you can see, we have done several customizations like:
1. setting the line-width, line-style, line-color.
2. setting the marker, markers face color, markers size.
3. overriding the x and y axis range. If overriding is not
done, pyplot module uses auto-scale feature to set the axis range
and scale.
"""

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

# importing the required modules


import matplotlib.pyplot as plt
import numpy as np

# setting the x - coordinates


x = np.arange(0, 2*(np.pi), 0.1)
# setting the corresponding y - coordinatey = np.sin(x)
y = np.sin(x)

# potting the points


plt.plot(x, y)

# function to show the plot


plt.show()
"""
Here, we use NumPy which is a general-purpose array-processing
package in python.
1. To set the x axis values, we use np.arange() method in
which rst two arguments are for range and third one for
2. step-wise increment. The result is a numpy array.
3. To get corresponding y-axis values, we simply use predened
np.sin() method on the numpy array.
4. Finally, we plot the points by passing x and y arrays to
the plt.plot() function.
"""

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

[1]: import numpy as np


import matplotlib.pyplot as plt
import helper
[2]: # Histogram
# frequencies
ages = [2,5,70,40,30,45,50,45,43,40,44,
60,7,13,57,18,90,77,32,21,20,40]

# setting the ranges and no. of intervals


range = (0, 100)
bins = 10

# 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')

# function to show the plot


plt.show()
""" Here, we use plt.hist() function to plot a histogram.
frequencies are passed as the ages list.
Range could be set by dening a tuple containing min and max value.
Next step is to bin the range of valuesthat is, divide the
entire range of values into a series of intervalsand then
count how many values fall into each interval. Here we have
dened bins = 10. So, there are a total of 100/10 = 10 intervals.
"""

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);

[8]: y,x,_ = plt.hist(helper.monthly_data_by_key(month=7, key='temperaturemax'));


plt.plot(x[:-1],y , lw=2);

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);

[13]: # Two-by-four array of samples from N(3, 6.25):


z= 2.5 * np.random.randn(2, 4) + 3
# z is a random variable with normal distribution with
# mean =3 and std. Dev. of 2.5 (variance = 6.25)
z
[13]: array([[2.60959735, 3.91983404, 3.40941625, 4.41309591],
[1.30923611, 4.93378532, 6.27361838, 5.02468585]])

Page 21 of 43
1.2.3. Bar Charts

November 2, 2019

[1]: import numpy as np


import matplotlib.pyplot as plt
[2]: # Bar Chart

# x-coordinates of left sides of bars


left = [1, 2, 3, 4, 5]

# heights of bars
height = [10, 24, 36, 40, 5]

# labels for bars


tick_label = ['one', 'two', 'three', 'four', 'five']

# plotting a bar chart


plt.bar(left, height, tick_label = tick_label,
width = 0.8, color = ['red', 'green'])

# naming the x-axis


plt.xlabel('x - axis')
# naming the y-axis
plt.ylabel('y - axis')
# plot title
plt.title('My bar chart!')

# function to show the plot


plt.show()
""" Here, we use plt.bar() function to plot a bar chart.
x-coordinates of left side of bars are passed along with heights of bars.
you can also give some name to x-axis coordinates by dening tick_labels
"""

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)

value_2018= np.array([month[1] for month in precip_sums_2018])


value_2017= np.array([month[1] for month in precip_sums_2017])
value_2016= np.array([month[1] for month in precip_sums_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);

[6]: #Stacked Horiozental Bar Chart


import numpy as np
import matplotlib.pyplot as plt
import helper

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)

value_2018= np.array([month[1] for month in precip_sums_2018])


value_2017= np.array([month[1] for month in precip_sums_2017])
value_2016= np.array([month[1] for month in precip_sums_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()

[8]: group_width = 0.7


offsets=[-group_width/3 , 0, group_width/3]
for index, key in enumerate(sorted(data.keys())):
plt.barh(np.arange(len(data[key]))-offsets[index],data[key],
height=group_width/3, label= str(key))
plt.yticks(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

[23]: import numpy as np


import matplotlib.pyplot as plt
[24]: wedges=np.array([8,20,30,52])
plt.pie(wedges, labels=['Blue','Orange','Green','Red']);
plt.show()

[25]: plt.pie(wedges, labels=['Blue','Orange','Green','Red'],


labeldistance=1.5);
plt.show()

Page 29 of 43
[26]:
# defining labels
activities = ['eat', 'sleep', 'work', 'play']

# portion covered by each label


slices = [3, 7, 8, 6]

# color for each label


colors = ['r', 'y', 'g', 'b']

# plotting the pie chart


plt.pie(slices, labels = activities, colors=colors,
startangle=90, shadow = True, explode = (0, 0, 0.1, 0),
radius = 1.2, autopct = '%1.1f%%')

# plotting legend
plt.legend()

# showing the plot


plt.show()
"""
1. Here, we plot a pie chart by using plt.pie() method.
2. First of all, we dene the labels using a list called activities.
3. Then, portion of each label can be dened using another list
called slices.

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);

[29]: plt.pie(totals, labels=helper.MONTHS, autopct='%.2f%%');

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)

sep_precip=[month[8][1] for month in [precip_2018,


precip_2017,precip_2016,precip_2015]]
labels=['2018','2017','2016','2015']
plt.pie(sep_precip, autopct='%.2f%%', labels=labels);

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

[1]: import numpy as np


import matplotlib.pyplot as plt
import random
import helper
from sklearn.datasets import make_blobs
# Installing sklearn in cmd: pip install -U scikit-learn
[2]: # x-axis values
x = [1,2,3,4,5,6,7,8,9,10]
# y-axis values
y = [2,4,5,7,6,8,9,11,12,12]

# plotting points as a scatter plot


plt.scatter(x, y, label= "stars", color= "green",
marker= "*", s=30)

# x-axis label
plt.xlabel('x - axis')
# frequency label
plt.ylabel('y - axis')
# plot title
plt.title('My scatter plot!')
# showing legend
plt.legend()

# function to show the plot


plt.show()
"""
1. Here, we use plt.scatter() function to plot a scatter plot.
2. Like a line, we dene x and corresponding y axis values here as well.
3. marker argument is used to set the character to use as marker. Its size
can be dened using s parameter.
"""

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]);

[9]: plt.scatter(avg_wind, min_temps);

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

You might also like