100% found this document useful (1 vote)
58 views15 pages

Plotting - Ipynb in

Nothing to say more

Uploaded by

ashish gupta
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
100% found this document useful (1 vote)
58 views15 pages

Plotting - Ipynb in

Nothing to say more

Uploaded by

ashish gupta
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/ 15

11/12/24, 10:54 PM Plotting.

ipynb - Colab

# Using matplotlib to make graphs with Python.


# Matplotlib is a Python package, which means that it’s a collection of modules with related functionality.
# Matplotlib doesn’t come built in with Python’s standard library, so you’ll have to install it
# If you are plotting in IDE, first installl Matplotlib type pip install matplotlib (Command Prompt on Windows or Terminal on

Start coding or generate with AI.

# pylab is a module that combines matplotlib.pyplot with numpy into a single namespace for convenience.
# it is generally discouraged because it imports many functions and variables globally, which may cause confusion or naming c
# While pylab is convenient for simple tasks, it's better to use matplotlib.pyplot directly for more complex projects

from pylab import plot, show

# Example data for the plot


x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# Creating the line plot


plot(x, y,marker='o') # makers = 'o','+','*','x'
# Markers highlight data points in a line plot.

# Display the plot


show()

plot(x, y,'o') #
# omitting marker=, we can plot only points
# there should be no line connecting the points.
show()

avg_percentage = [50,55,49,60,59,68,70,79,81,75,85,90,95]
print(len(avg_percentage))
plot(avg_percentage)
show()
years=range(2010,2023)
plot(avg_percentage,years)

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 1/15
11/12/24, 10:54 PM Plotting.ipynb - Colab

13

# three plot on a single graph


from pylab import plot, show, title, xlabel, ylabel, legend
nyc_temp_2000 = [31.3, 37.3, 47.2, 51.0, 63.5, 71.3, 72.3, 72.7, 66.0 , 57.0, 45.3, 31.1]
nyc_temp_2006 = [40.9, 35.7, 43.1, 55.7, 63.1, 71.0, 77.9, 75.8, 66.6 , 56.2, 51.9, 43.6]
nyc_temp_2012 = [37.3, 40.9, 50.9, 54.8, 65.1, 71.0, 78.8, 76.7, 68.8 , 58.0, 43.9, 41.5]
months = range(1,13)
plot(months, nyc_temp_2000, months, nyc_temp_2006, months, nyc_temp_2012)
title('Average monthly temperature in NYC')
xlabel('Month')
ylabel('Temperature')
# After plot command import legend from pylab
# You can specify a particular position, such as 'lower center', 'center left', and'upper left'.
# You can set the position to 'best', and the legend will be positioned so as not to interfere with the graph.
from [<matplotlib.lines.Line2D
pylab import legend at 0x7ed1582ee980>]
legend([2000, 2006, 2012])
show()

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 2/15
11/12/24, 10:54 PM Plotting.ipynb - Colab

# Customizing the Axes


# you can use xmin, xmax, and ymax to set the minimum and maximum values for the x-axis and the maximum value for the y-axis
# axis([0, 10, 0, 20]). This would set the range of the x-axis to (0, 10) and that of the y-axis to (0, 20).
from pylab import plot, show, axis
nyc_temp_2012 = [37.3, 40.9, 50.9, 54.8, 65.1, 71.0, 78.8, 76.7, 68.8 , 58.0, 43.9, 41.5]
plot(nyc_temp_2012, marker='o')
# axis()

axis(ymin=0)
show()

# how to save plot in pylab


from pylab import plot, show, title, xlabel, ylabel, legend, savefig
nyc_temp_2000 = [31.3, 37.3, 47.2, 51.0, 63.5, 71.3, 72.3, 72.7, 66.0 , 57.0, 45.3, 31.1]
nyc_temp_2006 = [40.9, 35.7, 43.1, 55.7, 63.1, 71.0, 77.9, 75.8, 66.6 , 56.2, 51.9, 43.6]
nyc_temp_2012 = [37.3, 40.9, 50.9, 54.8, 65.1, 71.0, 78.8, 76.7, 68.8 , 58.0, 43.9, 41.5]
months = range(1,13)
plot(months, nyc_temp_2000, months, nyc_temp_2006, months, nyc_temp_2012)
title('Average monthly temperature in NYC')
xlabel('Month')
ylabel('Temperature')
# After plot command import legend from pylab
# You can specify a particular position, such as 'lower center', 'center left', and'upper left'.
# You can set the position to 'best', and the legend will be positioned so as not to interfere with the graph.
from pylab import legend
legend([2000, 2006, 2012])
savefig("pylab_plot.png")
# For PDF: savefig("plot.pdf")
show()
# If you're using Google Colab and want to download the saved plot to your computer
from google.colab import files

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 3/15
11/12/24, 10:54 PM Plotting.ipynb - Colab
# Download the saved plot
files.download("pylab_plot.png")

# plot using Matplotlib


# If you are plotting in IDE, first installl Matplotlib type pip install matplotlib (Command Prompt on Windows or Terminal o

import matplotlib.pyplot as plt


x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Creating a line plot
plt.plot(x, y)

# Adding titles and labels


plt.title("Simple Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")

# Displaying the plot


plt.show()

# Customizing the line plot with markers and colors


plt.plot(x, y, color='green', marker='*', linewidth=4, linestyle='dashed')

# Displaying the plot


plt.show()

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 4/15
11/12/24, 10:54 PM Plotting.ipynb - Colab

import matplotlib.pyplot as plt


from google.colab import files
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Creating a line plot
plt.plot(x, y)
plt.savefig("line_plot1.png")
files.download("line_plot1.png")

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 5/15
11/12/24, 10:54 PM Plotting.ipynb - Colab
# NumPy

# NumPy is the core Python package for numerical computing


# main features of NumPy are: n-dimensional array object ndarray
# To get started with NumPy, let's adopt the standard convention and import it using the name np:

import numpy as np
a=np.array([2,3,5,7,11])
print(a)
type(a)
a
list1=[2,3,5,7,11]
print(list1)
# NumPy array it looks a lot like a Python list except that the entries are
# separated by spaces whereas entries in a Python list are separated by commas.

[ 2 3 5 7 11]
[2, 3, 5, 7, 11]

# Matplotlib and NumPy are essential libraries in Python for data visualization and numerical computing.
# NumPy: Used for creating and handling large, multi-dimensional arrays and matrices of data. It provides mathematical funct
# Matplotlib: Used for plotting graphs and visualizing data. Matplotlib works well with NumPy arrays for data organization a
# how to import
import numpy as np
import matplotlib.pyplot as plt

# Organizing data using NumPy arrays


x = np.linspace(0, 10, 100) # 100 points between 0 and 10
y = np.sin(x) # Sine wave

# Plotting using Matplotlib


plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()

plt.plot(x, y, label='Sine Wave', color='r') # Red sine wave


plt.legend()
plt.show()

plt.plot(x, y, marker='o', linestyle='-', color='b') # Blue line with circle markers


plt.show()

y1=np.sin(x)
y2=np.cos(x)
plt.plot(x, y1, label='Sine Wave', color='r')
plt.plot(x, y2, label='Cos Wave', color='b')
plt.legend()
plt.show

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 6/15
11/12/24, 10:54 PM Plotting.ipynb - Colab

x=

# Bar Chart
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 5, 9]

plt.bar(categories, values)
plt.title("Bar Chart Example")
plt.xlabel('categories')
plt.ylabel('values')
plt.show()

# horizontal bar chart


plt.barh(categories, values)
plt.title("Horizontal Bar Chart")
matplotlib.pyplot.show
plt.xlabel('values')
def show(*args, **kwargs)
plt.ylabel('categories')
plt.show()
Display all open figures.

Parameters
colors=['red','green','blue','purple']
----------
plt.bar(categories, values,color=colors)
block : bool, optional
plt.show()
Whether to wait for all figures to be closed before returning.

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 7/15
11/12/24, 10:54 PM Plotting.ipynb - Colab

# Contour plots show three-dimensional data in two dimensions by plotting constant values (contours).
# Use contour() for 2D contour plots.
X, Y = np.meshgrid(np.linspace(-5, 5, 100), np.linspace(-5, 5, 100))
Z = np.sin(np.sqrt(X**2 + Y**2))

plt.contour(X, Y, Z) # Contour plot with color map


plt.colorbar()
plt.title("Contour Plot")
plt.show()

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 8/15
11/12/24, 10:54 PM Plotting.ipynb - Colab

#Fields
# Field plots, such as vector fields, use quiver() to visualize vector data.
X, Y = np.meshgrid(np.linspace(-5, 5, 10), np.linspace(-5, 5, 10))
U = -Y
V = X

plt.quiver(X, Y, U, V) # Vector field plot


plt.title("Vector Field")
plt.show()

# Managing Subplots and Axes


# Subplots allow multiple plots in one figure. You can create subplots using plt.subplot() or plt.subplots().
# Creating a 2x1 grid of subplots
# plt.subplot(nrows, ncols, index)
# nrows: The number of rows in the subplot grid.
# ncols: The number of columns in the subplot grid.
# index: The position of the current subplot in the grid (starting from 1).

plt.subplot(2, 2, 1)
plt.plot(x, np.sin(x),label='sin(x)',color='r') # First subplot (Sine wave)

plt.subplot(2, 2, 2)
plt.plot(x, np.cos(x),label='cos(x)',color='b') # Second subplot (Cosine wave)

plt.subplot(2, 2, 3)
plt.plot(x, np.sin(2*x),label='sin(2x)',color= 'r') # First subplot (Sine wave)

plt.subplot(2, 2, 4)
plt.plot(x, np.cos(2*x),label='cos(2x)',color='b') # Second subplot (Cosine wave)

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 9/15
11/12/24, 10:54 PM Plotting.ipynb - Colab

Text(0.5, 1.0, '-cos wave')

import matplotlib.pyplot as plt


import numpy as np
x=np.linspace(-2,2,100)
y1=np.sin(x)
y2=np.cos(x)
y3=-np.sin(x)
y4=-np.cos(x)
# First Subplot
plt.subplot(2,2,1)
plt.plot(x,y1)
plt.title('sin wave')
# Second Subplot
plt.subplot(2,2,2)
plt.plot(x,y2)
plt.title('cos wave')
# Third Subplot
plt.subplot(2,2,3)
plt.plot(x,y3)
plt.title('-sin wave')
# Fourth Subplot
plt.subplot(2,2,4)
plt.plot(x,y4)
plt.title('-cos wave')
plt.tight_layout()

# subplots()
# This function returns a figure object and an array of axes objects for more advanced subplot management.
# fig, axs = plt.subplots(nrows, ncols, figsize, sharex, sharey)
https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 10/15
11/12/24, 10:54 PM Plotting.ipynb - Colab
# nrows: Number of rows of subplots.
# ncols: Number of columns of subplots.
# fig: The figure object, which contains all subplots.
# fig: Represents the entire figure, which contains all subplots.
# axs: An array of axes objects, one for each subplot.
# axs: This is an array of axes objects (a 2D array in this case). Each element of axs corresponds to one subplot.#

fig, axs = plt.subplots(2, 2) # 2x2 grid of subplots

axs[0, 0].plot(x, np.sin(x)) # First subplot


axs[0, 1].plot(x, np.cos(x)) # Second subplot
axs[1, 0].plot(x, -np.sin(x)) # Third subplot
axs[1, 1].plot(x, -np.cos(x)) # Fourth subplot

plt.show()

# Histogram
import matplotlib.pyplot as plt

# Basic dataset: Exam scores of students


exam_scores = [45, 56, 67, 78, 89, 55, 66, 77, 88, 99, 56, 67, 78, 89, 45, 56, 67, 78, 89, 90, 100]

# Plot the histogram


plt.hist(exam_scores, bins=10, color='blue', edgecolor='black', alpha=0.7)

# Add titles and labels


plt.title('Histogram of Exam Scores')
plt.xlabel('Score')
plt.ylabel('Frequency')

# Show the plot


plt.show()

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 11/15
11/12/24, 10:54 PM Plotting.ipynb - Colab

import matplotlib.pyplot as plt

# Basic dataset: Exam scores of students


exam_scores = [45, 56, 67, 78, 89, 55, 66, 77, 88, 99, 56, 67, 78, 89, 45, 56, 67, 78, 89, 90, 100]

# Define custom bin edges


bins = [40, 50, 60, 70, 80, 90, 100]

# Plot the histogram


plt.hist(exam_scores, bins=bins, color='green', edgecolor='black', alpha=0.7)

# Add titles and labels


plt.title('Histogram of Exam Scores with Custom Bins')
plt.xlabel('Score Range')
plt.ylabel('Frequency')

# Show the plot


plt.show()

# Creating a Pie Chart


# Data for Pie Chart
labels_1 = ['A', 'B', 'C', 'D','E']
sizes = [20, 30, 25, 25, 20]

# Pie Chart
plt.pie(sizes, labels=labels_1, autopct='%1.1f%%')
plt.title("Pie Chart Example")
plt.show()

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 12/15
11/12/24, 10:54 PM Plotting.ipynb - Colab

import numpy as np
import matplotlib.pyplot as plt

# Define decay function


def decay(Q0, lam, t):
return Q0 * np.exp(-lam * t)

# Example usage
Q0 = 100 # Initial quantity
lam = 0.1 # Decay constant
t = np.linspace(0, 10, 100) # Time range

Q_t = decay(Q0, lam, t)

plt.plot(t, Q_t)
plt.title('Exponential Decay')
plt.xlabel('Time')
plt.ylabel('Quantity')
plt.show()

# Animation of decay
# N = N_0 exp(-lamda *t) where N_0 is initial quantity, lamda is a rate and t is time
# Import required libraries:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML # For displaying the animation in Colab

# Decay function
def decay(t, N0, decay_rate):
result = N0 * np.exp(-decay_rate * t)
return result

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 13/15
11/12/24, 10:54 PM Plotting.ipynb - Colab
# fig, axs = plt.subplots(nrows, ncols, figsize, sharex, sharey)
# nrows: Number of rows of subplots.
# ncols: Number of columns of subplots.
# fig: The figure object, which contains all subplots.
# fig: Represents the entire figure, which contains all subplots.
# axs: An array of axes objects, one for each subplot.
# axs: This is an array of axes objects (a 2D array in this case). Each element of axs corresponds to one subplot.
# Set up figure and axis

fig, ax = plt.subplots()
ax.set_xlim(0, 10) # Time range from 0 to 10
ax.set_ylim(0, 1.0) # Decay value from 0 to 1
line, = ax.plot([], [], lw=2)

# Initialization function
def init():
line.set_data([], [])
return line,

# Update function
def update(frame):
t = np.linspace(0, frame, 100) # Generate time values
N = decay(t, N0=1, decay_rate=0.5) # Calculate decay values
line.set_data(t, N)
return line,

# Create the animation


ani = FuncAnimation(fig, update, frames=np.linspace(0, 10, 200), init_func=init, blit=True)
# blit=True: Ensures that only parts of the plot that change are redrawn (improves performance).

# Render the animation in the notebook


HTML(ani.to_jshtml()) # Converts animation to HTML for display in Colab

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 14/15
11/12/24, 10:54 PM Plotting.ipynb - Colab

# Bayes Theorem
# To create a set in Python, we can use the FiniteSet class from the sympy package,
from sympy import FiniteSet
s = FiniteSet(2, 4, 6)
print(s)

{2, 4, 6}

from sympy import FiniteSet


from fractions import Fraction
s = FiniteSet(1, 1.5, Fraction(1, 5))
print(s)
print(len(s))
# Is this number in this set?”
print(4 in s)

# Empty Set
s1=FiniteSet()
print(s1)

{1/5, 1, 1.5}
3
False
        
EmptySet
Once Loop Reflect

https://colab.research.google.com/drive/1sbeHOEYdNkpSSXSoX8Jn0OVEjL4xYsAe#printMode=true 15/15

You might also like