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

Python Assignment Unit 2

The document contains code snippets demonstrating various plotting tasks in Python using libraries like NumPy and Matplotlib: 1) Plotting a sine wave with different markers and colors. 2) Plotting the tangent function and marking singular points. 3) Plotting a circle using polar coordinates. 4) Analyzing a triangular wave signal using Fourier series. 5) Calculating and plotting the sine function using a Maclaurin series. 6) Plotting a quadratic function and marking points. 7) Plotting cosine functions in polar coordinates for even and odd values of k.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python Assignment Unit 2

The document contains code snippets demonstrating various plotting tasks in Python using libraries like NumPy and Matplotlib: 1) Plotting a sine wave with different markers and colors. 2) Plotting the tangent function and marking singular points. 3) Plotting a circle using polar coordinates. 4) Analyzing a triangular wave signal using Fourier series. 5) Calculating and plotting the sine function using a Maclaurin series. 6) Plotting a quadratic function and marking points. 7) Plotting cosine functions in polar coordinates for even and odd values of k.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

1.Plot a sine wave using markers +, o, and x using three different colors.

In [4]: import numpy as np


import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)


y = np.sin(x)
plt.plot(x, y, marker='+', color='blue', label='Marker +')
plt.plot(x, y + 0.5, marker='o', color='green', label='Marker o')
plt.plot(x, y - 0.5, marker='x', color='red', label='Marker x')

plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sine Wave with Different Markers and Colors')
plt.legend()

plt.grid(True)
plt.show()

2.Plot tan θ, for θ from −2π to 2π, watch for singular points

In [3]: import numpy as np


import matplotlib.pyplot as plt
theta = np.linspace(-2 * np.pi, 2 * np.pi, 1000)
theta = theta[~np.isin(theta, [-np.pi/2, np.pi/2, 3*np.pi/2])]

tan_theta = np.tan(theta)

plt.figure(figsize=(8, 4))
plt.plot(theta, tan_theta, label='tan(θ)', color='blue')
plt.scatter([-np.pi/2, np.pi/2, 3*np.pi/2], [np.inf, -np.inf, np.inf], color='red',

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 1/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2
plt.axhline(y=0, color='black', linestyle='--', linewidth=0.5)
plt.xlabel('θ')
plt.ylabel('tan(θ)')
plt.title('Plot of tan(θ) for -2π ≤ θ ≤ 2π')
plt.xlim(-2 * np.pi, 2 * np.pi)
plt.ylim(-10, 10)
plt.grid(True)
plt.legend()
plt.show()

. Plot a circle using the polar() function.

In [11]: import numpy as np


import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 1000)
radius = np.ones(1000)
plt.polar(theta, radius)
plt.show()

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 2/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

In [18]: import numpy as np


from scipy.signal import triang
import matplotlib.pyplot as plt
from scipy.integrate import simps
L=1
samples=501
terms=50

x=np.linspace(0,L,samples,endpoint=False)
y=triang(samples)

a0=2./L*simps(y,x)
an=lambda n:2.0/L*simps(y*np.cos(2.*np.pi*n*x/L),x)
bn=lambda n:2.0/L*simps(y*np.sin(2.*np.pi*n*x/L),x)

s=a0/2.+sum([an(k)*np.cos(2.*np.pi*k*x/L)+bn(k)*np.sin(2.*np.pi*k*x/L)
for k in range(1,terms+1)])

plt.plot(x,s,label="Fourier series")
plt.plot(x,y,label="Original Triangular wave")
plt.xlabel("$x$")
plt.ylabel("$y=f(x)$")
plt.legend(loc='best',prop={'size':10})
plt.title("Triangular wave signal analysis by Fouries series")
plt.savefig("fs_triangular.png")
plt.show()

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 3/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[18], line 19
14 bn=lambda n:2.0/L*simps(y*np.sin(2.*np.pi*n*x/L),x)
16 s=a0/2.+sum([an(k)*np.cos(2.*np.pi*k*x/L)+bn(k)*np.sin(2.*np.pi*k*x/L)
17 for k in range(1,terms+1)])
---> 19 plt.plot(x,s,label="Fourier series")
20 plt.plot(x,y,label="Original Triangular wave")
21 plt.xlabel("$x$")

File ~\anaconda3\Lib\site-packages\matplotlib\pyplot.py:2812, in plot(scalex, scal


ey, data, *args, **kwargs)
2810 @_copy_docstring_and_deprecators(Axes.plot)
2811 def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
-> 2812 return gca().plot(
2813 *args, scalex=scalex, scaley=scaley,
2814 **({"data": data} if data is not None else {}), **kwargs)

File ~\anaconda3\Lib\site-packages\matplotlib\axes\_axes.py:1688, in Axes.plot(sel


f, scalex, scaley, data, *args, **kwargs)
1445 """
1446 Plot y versus x as lines and/or markers.
1447
(...)
1685 (``'green'``) or hex strings (``'#008000'``).
1686 """
1687 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1688 lines = [*self._get_lines(*args, data=data, **kwargs)]
1689 for line in lines:
1690 self.add_line(line)

File ~\anaconda3\Lib\site-packages\matplotlib\axes\_base.py:311, in _process_plot_


var_args.__call__(self, data, *args, **kwargs)
309 this += args[0],
310 args = args[1:]
--> 311 yield from self._plot_args(
312 this, kwargs, ambiguous_fmt_datakey=ambiguous_fmt_datakey)

File ~\anaconda3\Lib\site-packages\matplotlib\axes\_base.py:504, in _process_plot_


var_args._plot_args(self, tup, kwargs, return_kwargs, ambiguous_fmt_datakey)
501 self.axes.yaxis.update_units(y)
503 if x.shape[0] != y.shape[0]:
--> 504 raise ValueError(f"x and y must have same first dimension, but "
505 f"have shapes {x.shape} and {y.shape}")
506 if x.ndim > 2 or y.ndim > 2:
507 raise ValueError(f"x and y can be no greater than 2D, but have "
508 f"shapes {x.shape} and {y.shape}")

ValueError: x and y must have same first dimension, but have shapes (50,) and (1,)

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 4/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

Generate a triangular wave using the Fourier series

Write a Python program to calculate the sine function using series expansion and plot it.

In [9]: import numpy as np


import matplotlib.pyplot as plt

def calculate_sine(x, num_terms=10):


sine_value = 0
for n in range(num_terms):
term = ((-1) ** n) * (x ** (2 * n + 1)) / np.math.factorial(2 * n + 1)
sine_value += term
return sine_value

x = np.linspace(-2 * np.pi, 2 * np.pi, 400)

sine_values = [calculate_sine(val, num_terms=10) for val in x]

plt.figure(figsize=(8, 4))
plt.plot(x, sine_values, label='Sine Function (Maclaurin Series)')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('Sine Function Plot Using Maclaurin Series')
plt.grid(True)
plt.axhline(y=0, color='black', linewidth=0.5)
plt.axvline(x=0, color='black', linewidth=0.5)
plt.legend()
plt.show()

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 5/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

Write a Python program to plot y = 5x^2 + 3x + 2 (for x from 0 to 5, 20 points), using

pylab, with axes and title. Use red colored circles to mark the points.

In [33]: from pylab import *

x = linspace(0, 5, 20)

y = 5 * x**2 + 3 * x + 2

plot(x, y, 'ro', label='y = 5x^2 + 3x + 2')

xlabel('x')
ylabel('y')
title('Plot of y = 5x^2 + 3x + 2')
grid(True)

legend()

show()

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 6/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

Write a program to plot r = cos(kθ) in polar coordinates for θ from 0 to 10π, k is an integer.
Write for two different values of k (even and odd).

In [31]: import numpy as np


import matplotlib.pyplot as plt

theta = np.linspace(0, 10 * np.pi, 1000)

k_even = 2
k_odd = 3

r_even = np.cos(k_even * theta)


r_odd = np.cos(k_odd * theta)

plt.subplot(121, projection='polar')
plt.plot(theta, r_even, label=f'r = cos({k_even}θ)', color='blue')
plt.title(f'r = cos({k_even}θ) in Polar Coordinates')
plt.legend()

plt.subplot(122, projection='polar')
plt.plot(theta, r_odd, label=f'r = cos({k_odd}θ)', color='green')
plt.title(f'r = cos({k_odd}θ) in Polar Coordinates')
plt.legend()

plt.tight_layout()
plt.show()

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 7/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

Write a Python program to plot a square wave using the Fourier series, number of terms
should be a variable.

In [13]: import numpy as np


import matplotlib.pyplot as plt

def square_wave_fourier(x, num_terms):


square_wave = 0
for n in range(1, num_terms + 1, 2): # Use only odd harmonics for a square wav
square_wave += (4 / (n * np.pi)) * np.sin(n * np.pi * x)
return square_wave

x = np.linspace(0, 2 * np.pi, 1000)

num_terms = 5
square_wave = square_wave_fourier(x, num_terms)

plt.figure(figsize=(8, 4))
plt.plot(x, square_wave, label=f'Square Wave (Terms = {num_terms})', color='blue')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Square Wave Approximation Using Fourier Series')
plt.grid(True)
plt.axhline(y=0, color='black', linewidth=0.5)
plt.axvline(x=0, color='black', linewidth=0.5)
plt.legend()
plt.show()

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 8/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

Write a Python program to read the x and y coordinates from a file, in a two-column format,
and plot them.

answer:First, ensure you have a file containing the x and y coordinates in a two-column
format. For example, you can have a file named coordinates.txt with the following content:

1.0 2.0 2.0 3.5 3.0 1.5 4.0 4.0 5.0 2.0

In [32]: import numpy as np


import matplotlib.pyplot as plt

file_path = r'C:\Users\aswin\Downloads\Book1.txt'

try:
data = np.loadtxt(file_path)
x = data[:, 0]
y = data[:, 1]

plt.scatter(x, y, marker='o', color='blue', label='Data Points')


plt.xlabel('X Coordinate')
plt.ylabel('Y Coordinate')
plt.title('Scatter Plot of X and Y Coordinates')
plt.grid(True)
plt.legend()
plt.show()

except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")

Cell In[32], line 19


plt.show()
^
SyntaxError: incomplete input

Plot x^2 + y^2 + z^2 = 25 using mayavi.

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 9/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

In [ ]: import numpy as np
from mayavi import mlab

def surface_equation(x, y):


return np.sqrt(25 - x**2 - y**2), -np.sqrt(25 - x**2 - y**2)

x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)

X, Y = np.meshgrid(x, y)

Z1, Z2 = surface_equation(X, Y)

surf = mlab.mesh(X, Y, Z1, color=(0.8, 0.2, 0.2))


surf = mlab.mesh(X, Y, Z2, color=(0.8, 0.2, 0.2))

mlab.xlabel("X")
mlab.ylabel("Y")
mlab.zlabel("Z")

# Show the plot


mlab.show()

C:\Users\aswin\AppData\Local\Temp\ipykernel_12260\1586635582.py:6: RuntimeWarning:
invalid value encountered in sqrt
return np.sqrt(25 - x**2 - y**2), -np.sqrt(25 - x**2 - y**2)

Make a plot z = sin(x) + sin(y) using imshow(), from −4π to 4π for both x and y.

In [26]: import numpy as np


import matplotlib.pyplot as plt

x = np.linspace(-4 * np.pi, 4 * np.pi, 400)


y = np.linspace(-4 * np.pi, 4 * np.pi, 400)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.sin(Y)

plt.imshow(Z, extent=(-4 * np.pi, 4 * np.pi, -4 * np.pi, 4 * np.pi), origin='lower


plt.colorbar(label='Z')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)
plt.show()

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 10/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

Write Python code to plot y = x^2 , with the axes labeled.

In [16]: import numpy as np


import matplotlib.pyplot as plt

x = np.linspace(-10, 10, 100)

y = x**2

plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.show()

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 11/12


10/4/23, 11:27 AM PYTHON ASSIGNMENT UNIT 2

In [24]: import numpy as np

x = 0.5
terms = 10

y = 0

# Calculate the series


for n in range(1, terms + 1):
numerator = (-1) ** n * x ** (2 * n + 1)
denominator = np.math.factorial(2 * n + 1)
term = numerator / denominator
y += term

print(f"The sum of the series for {terms} terms is: {y}")

The sum of the series for 10 terms is: -0.020574461395797005

In [ ]:

localhost:8888/nbconvert/html/Jedi/PYTHON ASSIGNMENT UNIT 2.ipynb?download=false 12/12

You might also like