Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

2D plots of cartesian and polar curves

Objectives:
1. To plot cartesian curves

3. To plot polar curves

3. To plot implicit functions, using python

Syntax used in this Lab:


plot(x, y): plot x and y using default line style and color

Customizations:
plot(x, y, 'bo'): plot x and y using blue circle markers
plot(y): plot y using x as index array 0..N-1
plot(y, 'r+'): ditto, but with red plusses
plot(x, y, 'go--', linewidth=2, markersize=12) ### plot(x, y, color='green', marker='o',
linestyle='dashed',linewidth=2,markersize=12)

Example: Plotting points(Scattered plot)

Syntax:
scatter(x_axis_data, y_axis_data, s=None, c=None, marker=None, cmap=None,vmin=None,
vmax=None, alpha=None, linewidths=None, edgecolors=None)

In [3]: # importing the required module


import matplotlib.pyplot as plt
x = [1,2,3,4,6,7,8] # x axis values
y = [2,7,9,1,5,10,3] # corresponding y axis values
plt.scatter(x, y) # plotting the points
plt.xlabel('x - axis') # naming the x axis
plt.ylabel('y - axis') # naming the y axis
plt.title('Scatter points') # giving a title to my graph
plt.show() # function to show the plot
Example: Plotting a line(Line plot)
In [6]: help(plt.plot)
Help on function plot in module matplotlib.pyplot:

plot(*args, scalex=True, scaley=True, data=None, **kwargs)


Plot y versus x as lines and/or markers.

Call signatures::

plot([x], y, [fmt], *, data=None, **kwargs)


plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

The coordinates of the points or line nodes are given by *x*, *y*.

The optional parameter *fmt* is a convenient way for defining basic


formatting like color, marker and linestyle. It's a shortcut string
notation described in the *Notes* section below.

>>> plot(x, y) # plot x and y using default line style and color
>>> plot(x, y, 'bo') # plot x and y using blue circle markers
>>> plot(y) # plot y using x as index array 0..N-1
>>> plot(y, 'r+') # ditto, but with red plusses

You can use `.Line2D` properties as keyword arguments for more


control on the appearance. Line properties and *fmt* can be mixed.
The following two calls yield identical results:

>>> plot(x, y, 'go--', linewidth=2, markersize=12)


>>> plot(x, y, color='green', marker='o', linestyle='dashed',
... linewidth=2, markersize=12)

When conflicting with *fmt*, keyword arguments take precedence.

**Plotting labelled data**

There's a convenient way for plotting objects with labelled data (i.e.
data that can be accessed by index ``obj['y']``). Instead of giving
the data in *x* and *y*, you can provide the object in the *data*
parameter and just give the labels for *x* and *y*::

>>> plot('xlabel', 'ylabel', data=obj)

All indexable objects are supported. This could e.g. be a `dict`, a


`pandas.DataFrame` or a structured numpy array.

**Plotting multiple sets of data**

There are various ways to plot multiple sets of data.

- The most straight forward way is just to call `plot` multiple times.
Example:

>>> plot(x1, y1, 'bo')


>>> plot(x2, y2, 'go')

- If *x* and/or *y* are 2D arrays a separate data set will be drawn
for every column. If both *x* and *y* are 2D, they must have the
same shape. If only one of them is 2D with shape (N, m) the other
must have length N and will be used for every data set m.

Example:

>>> x = [1, 2, 3]
>>> y = np.array([[1, 2], [3, 4], [5, 6]])
>>> plot(x, y)

is equivalent to:

>>> for col in range(y.shape[1]):


... plot(x, y[:, col])

- The third way is to specify multiple sets of *[x]*, *y*, *[fmt]*


groups::

>>> plot(x1, y1, 'g^', x2, y2, 'g-')

In this case, any additional keyword argument applies to all


datasets. Also this syntax cannot be combined with the *data*
parameter.

By default, each line is assigned a different style specified by a


'style cycle'. The *fmt* and line property parameters are only
necessary if you want explicit deviations from these defaults.
Alternatively, you can also change the style cycle using
:rc:`axes.prop_cycle`.

Parameters
----------
x, y : array-like or scalar
The horizontal / vertical coordinates of the data points.
*x* values are optional and default to ``range(len(y))``.

Commonly, these parameters are 1D arrays.

They can also be scalars, or two-dimensional (in that case, the


columns represent separate data sets).

These arguments cannot be passed as keywords.

fmt : str, optional


A format string, e.g. 'ro' for red circles. See the *Notes*
section for a full description of the format strings.

Format strings are just an abbreviation for quickly setting


basic line properties. All of these and more can also be
controlled by keyword arguments.

This argument cannot be passed as keyword.

data : indexable object, optional


An object with labelled data. If given, provide the label names to
plot in *x* and *y*.

.. note::
Technically there's a slight ambiguity in calls where the
second label is a valid *fmt*. ``plot('n', 'o', data=obj)``
could be ``plt(x, y)`` or ``plt(y, fmt)``. In such cases,
the former interpretation is chosen, but a warning is issued.
You may suppress the warning by adding an empty format string
``plot('n', 'o', '', data=obj)``.

Returns
-------
list of `.Line2D`
A list of lines representing the plotted data.

Other Parameters
----------------
scalex, scaley : bool, default: True
These parameters determine if the view limits are adapted to the
data limits. The values are passed on to `autoscale_view`.

**kwargs : `.Line2D` properties, optional


*kwargs* are used to specify properties like a line label (for
auto legends), linewidth, antialiasing, marker face color.
Example::

>>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2)


>>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')

If you specify multiple lines with one plot call, the kwargs apply
to all those lines. In case the label object is iterable, each
element is used as labels for each set of data.

Here is a list of available `.Line2D` properties:

Properties:
agg_filter: a filter function, which takes a (m, n, 3) float array and a d
pi value, and returns a (m, n, 3) array
alpha: scalar or None
animated: bool
antialiased or aa: bool
clip_box: `.Bbox`
clip_on: bool
clip_path: Patch or (Path, Transform) or None
color or c: color
dash_capstyle: `.CapStyle` or {'butt', 'projecting', 'round'}
dash_joinstyle: `.JoinStyle` or {'miter', 'round', 'bevel'}
dashes: sequence of floats (on/off ink in points) or (None, None)
data: (2, N) array or two 1D arrays
drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-pos
t'}, default: 'default'
figure: `.Figure`
fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'}
gid: str
in_layout: bool
label: object
linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth or lw: float
marker: marker style string, `~.path.Path` or `~.markers.MarkerStyle`
markeredgecolor or mec: color
markeredgewidth or mew: float
markerfacecolor or mfc: color
markerfacecoloralt or mfcalt: color
markersize or ms: float
markevery: None or int or (int, int) or slice or list[int] or float or (fl
oat, float) or list[bool]
path_effects: `.AbstractPathEffect`
picker: float or callable[[Artist, Event], tuple[bool, dict]]
pickradius: float
rasterized: bool
sketch_params: (scale: float, length: float, randomness: float)
snap: bool or None
solid_capstyle: `.CapStyle` or {'butt', 'projecting', 'round'}
solid_joinstyle: `.JoinStyle` or {'miter', 'round', 'bevel'}
transform: unknown
url: str
visible: bool
xdata: 1D array
ydata: 1D array
zorder: float
See Also
--------
scatter : XY scatter plot with markers of varying size and/or color (
sometimes also called bubble chart).

Notes
-----
**Format Strings**

A format string consists of a part for color, marker and line::

fmt = '[marker][line][color]'

Each of them is optional. If not provided, the value from the style
cycle is used. Exception: If ``line`` is given, but no ``marker``,
the data will be a line without markers.

Other combinations such as ``[color][marker][line]`` are also


supported, but note that their parsing may be ambiguous.

**Markers**

============= ===============================
character description
============= ===============================
``'.'`` point marker
``','`` pixel marker
``'o'`` circle marker
``'v'`` triangle_down marker
``'^'`` triangle_up marker
``'<'`` triangle_left marker
``'>'`` triangle_right marker
``'1'`` tri_down marker
``'2'`` tri_up marker
``'3'`` tri_left marker
``'4'`` tri_right marker
``'8'`` octagon marker
``'s'`` square marker
``'p'`` pentagon marker
``'P'`` plus (filled) marker
``'*'`` star marker
``'h'`` hexagon1 marker
``'H'`` hexagon2 marker
``'+'`` plus marker
``'x'`` x marker
``'X'`` x (filled) marker
``'D'`` diamond marker
``'d'`` thin_diamond marker
``'|'`` vline marker
``'_'`` hline marker
============= ===============================

**Line Styles**

============= ===============================
character description
============= ===============================
``'-'`` solid line style
``'--'`` dashed line style
``'-.'`` dash-dot line style
``':'`` dotted line style
============= ===============================
Example format strings::

'b' # blue markers with default shape


'or' # red circles
'-g' # green solid line
'--' # dashed line with default color
'^k:' # black triangle_up markers connected by a dotted line

**Colors**

The supported color abbreviations are the single letter codes

============= ===============================
character color
============= ===============================
``'b'`` blue
``'g'`` green
``'r'`` red
``'c'`` cyan
``'m'`` magenta
``'y'`` yellow
``'k'`` black
``'w'`` white
============= ===============================

and the ``'CN'`` colors that index into the default property cycle.

If the color is the only part of the format string, you can
additionally use any `matplotlib.colors` spec, e.g. full names
(``'green'``) or hex strings (``'#008000'``).

In [5]: # importing the required module


import matplotlib.pyplot as plt
x = [1,2,3,4,6,7,8] # x axis values
y = [2,7,9,1,5,10,3] # corresponding y axis values
plt.plot(x, y, 'r+--') # plotting the points
plt.xlabel('x - axis') # naming the x axis
plt.ylabel('y - axis') # naming the y axis
plt.title('My first graph!') # giving a title to my graph
plt.show() # function to show the plot

Functions
1. Exponential curve
In [7]: # importing the required modules
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10, 10, 0.001) # x takes the values between -10 and 10 with a step l
y = np.exp(x) # Exponential function

plt.plot(x,y) # plotting the points


plt.title("Exponential curve ") # giving a title to the graph
plt.grid() # displaying the grid
plt.show() # shows the plot

2. sine and cos curves


In [8]: x = np.arange(-10, 10, 0.001)
y1 = np.sin(x)
y2=np.cos(x)
plt.plot(x,y1,x,y2) # plotting sin and cos function together with same values of x
plt.title("sine curve and cosine curve")
plt.xlabel("Values of x")
plt.ylabel("Values of sin(x) and cos(x) ")
plt.grid()
plt.show()
In [10]: # A simple graph
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2, 100) # np.linspace()is a tool in Python for creating numeric
plt.plot(x, x, label='linear') # Plot some data on the axes.
plt.plot(x, x**2, label='quadratic') # Plot more data on the axes...
plt.plot(x, x**3, label='cubic') # ... and some more.
plt.xlabel('x label') # Add an x-label to the axes.
plt.ylabel('y label') # Add a y-label to the axes.
plt.title("Simple Plot") # Add a title to the axes.
plt.legend() # Add a legend
plt.show()

Implicit Function
Syntax:
plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0, points=300,
line_color='blue', show=True, **kwargs)

expr : The equation / inequality that is to be plotted.

x_var (optional) : symbol to plot on x-axis or tuple giving symbol and range as (symbol,
xmin, xmax)

y_var (optional) : symbol to plot on y-axis or tuple giving symbol and range as (symbol,
ymin, ymax)

If neither x_var nor y_var are given then the free symbols in the expression will be
assigned in the order they are sorted.

The following keyword arguments can also be used:

** adaptive: Boolean. The default value is set to True. It has to beset to False if you want
to use a mesh grid.

** depth : integer. The depth of recursion for adaptive mesh grid. Default value is 0.
Takes value in the range (0, 4).
** points: integer. The number of points if adaptive mesh grid is not used. Default value
is 300.

** show: Boolean. Default value is True. If set to False, the plot will not be shown. See
Plot for further information.
title string. The title for the plot.

xlabel string. The label for the x-axis

ylabel string. The label for the y-axis

Aesthetics options:

line_color: float or string. Specifies the color for the plot

Plot the following :


1. Circle: x 2
+ y
2
= 5

In [11]: # importing Sympy package with plot_implicit, symbols and Eq functions only
# symbols: used to declare variable as symbolic expression
# Eq: sets up an equation. Ex: 2x-y=0 is written as Eq(2*x-y,0)

from sympy import plot_implicit, symbols, Eq


x, y = symbols('x y')

In [12]: p1 = plot_implicit(Eq(x**2 + y**2, 4),(x,-4,4),(y,-4,4),title= 'Circle: $x^2+y^2=4$

2 2 2

2. Astroid: x 3
+ y 3
= a3 ,a > 0

In [ ]: p2 = plot_implicit(
Eq(x**(2/3) + y**(2/3), 3**(2/3)), (x, -5, 5), (y, -5, 5),title= 'Astroid: $x^{
3. Strophoid:
2 2
y (a − x) = x (a + x), a > 0

In [ ]: p3= plot_implicit(


Eq((y**2)*(2-x), (x**2)*(2+x)), (x, -5, 5), (y, -5, 5),title= 'Strophoid: $y^2

4. Cissiod: y 2
(a − x) = x , a > 0
3

In [ ]: p4=plot_implicit(
Eq((y**2)*(3-x),x**3),(x,-2,5),(y,-5,5)) # a=3
5. Leminscate: a 2
y
2 2
= x (a
2
− x )
2

In [ ]: p5=plot_implicit(
Eq(4*(y**2),(x**2)*(4-x**2)),(x,-5,5),(y,-5,5)) # a=2

6. Folium of De-Cartes: x 3
+ y
3
= 3axy

In [ ]: p6=plot_implicit(
Eq(x**3+y**3,3*2*x*y),(x,-5,5),(y,-5,5)) # a=2
Polar Curves
The matplotlib.pyplot.polar() function in pyplot
module of matplotlib python library is used to plot
the curves in polar coordinates.

Syntax: matplotlib.pyplot.polar(theta, r, **kwargs)


Theta: This is the angle at which we want to draw the curve.
r: It is the distance.

1. Circle: r = p, Where p is the radius of the


circle
In [ ]: import numpy as np
import matplotlib.pyplot as plt
plt.axes(projection = 'polar')
r = 3
rads = np.arange(0, (2 * np.pi), 0.01)
# plotting the circle
for i in rads:
plt.polar(i, r, 'g.')
plt.show()
2. Circle: x = 5cosθ; y = 5sinθ

In [ ]: #Plot circle in polar form


import numpy as np
from pylab import *
theta=linspace(0,2*np.pi,1000) #theta values calculated 1000 points from 0 to 2pi
x=5*cos(theta)
y=5*sin(theta)
r=sqrt(x**2+y**2)
polar(theta,r,'r.')
show()

3. Cardiod: r = 5(1 + cosθ)

In [15]: #Plot cardiod r=5(1+cos theta)


from pylab import *
theta=linspace(0,2*np.pi,1000)
r1=5+5*cos(theta)

polar(theta,r1,'g')

show()
4. Four leaved Rose: r = 2|cos2x|

In [ ]: #Plot Four Leaved Rose r=2 |cos2x|


from pylab import *
theta=linspace(0,2*pi,1000)
r=2*abs(cos(2*theta))
polar(theta,r,'r')
show()

5. Ellipse: r =
2
ab
2
√asin (θ)+bcos (θ)

In [ ]: import numpy as np


import matplotlib.pyplot as plt
import math

plt.axes(projection = 'polar')

a = 5
b = 2

rad = np.arange(0, (2 * np.pi), 0.01)


# plotting the ellipse
for i in rad:
r = (a*b)/math.sqrt((a*np.sin(i))**2 + (b*np.cos(i))**2)
plt.polar(i, r, 'g.')

# display the polar plot


plt.show()

6. Cardiod: r = a + acos(θ) and


r = a − acos(θ)

In [ ]: import numpy as np


import matplotlib.pyplot as plt
import math

plt.axes(projection = 'polar')
a=3

rad = np.arange(0, (2 * np.pi), 0.01)

# plotting the cardioid


for i in rad:
r = a + (a*np.cos(i))
plt.polar(i,r,'g.')
r1=a-(a*np.cos(i))
plt.polar(i,r1,'r.')

# display the polar plot


plt.show()
Parametric Equation

1. Circle: x = acos(θ); y = asin(θ)

In [ ]: def circle(r):


x = [] #create the list of x coordinates
y = [] #create the list of y coordinates

for theta in np.linspace(-2*np.pi, 2*np.pi, 100): #loop over a list of theta, whi
x.append(r*np.cos(theta)) #add the corresponding expression of x to the x list
y.append(r*np.sin(theta)) #same for y

plt.plot(x,y) #plot using matplotlib.piplot


plt.show() #show the plot

circle(5) #call the function

2. Cycloid:
x = a(θ − sinθ); y = a(1 − sinθ)

In [ ]: def cycloid(r):


x = [] #create the list of x coordinates
y = [] #create the list of y coordinates

for theta in np.linspace(-2*np.pi, 2*np.pi, 100): #loop over a list of theta, whi
x.append(r*(theta - np.sin(theta))) #add the corresponding expression of x to t
y.append(r*(1 - np.cos(theta))) #same for y

plt.plot(x,y) #plot using matplotlib.piplot


plt.show() #show the plot

cycloid(2) #call the function

Exercise:
Plot the following:
Parabola y 2
= 4ax
2
2
y
Hyperbola
x
− = 1
2 2
a b

Lower half of the circle: x 2


+ 2x = 4 + 4y − y
2

πx
cos( )
2
π
1 + sin(x + )
4

Spiral of Archimedes: r = a + bθ *Limacon: r = a + bcosθ

In [ ]:

Cardioid as a general case


In [ ]: from numpy import *
import matplotlib.pyplot as plt
fig=plt.figure()
fig.add_subplot(121,projection='polar')
plt.title('cardioid in polar form : radius=a+(b*cos(k*radian))')
r=arange(0,2*pi,.01)
a,b,k=1,2,1
for radian in r:
radius=a+(b*cos(k*radian))
plt.polar(radian,radius,'*','b')
plt.show()
In [ ]:

In [ ]:

In [ ]:

You might also like