0% found this document useful (0 votes)
33 views10 pages

Unit V Anseer Key

Python data science ans key

Uploaded by

priyajenat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views10 pages

Unit V Anseer Key

Python data science ans key

Uploaded by

priyajenat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Unit V

16marks

1. Outline any two three-dimensional plotting in Matpoltlib with an example.

Three-dimensional plotting in Matplotlib is done using the Axes3D module.

. Surface Plot

A surface plot is a three-dimensional plot that displays a surface defined by a function z=f(x,y)z = f(x, y).
It is used to visualize the relationship between three variables.

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

import numpy as np

# Generate data

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

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

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

z = np.sin(np.sqrt(x**2 + y**2))

# Create a figure and a 3D axis

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

# Plot a surface

ax.plot_surface(x, y, z, cmap='viridis')
# Labels

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

ax.set_title('Surface Plot')

plt.show()

2. 3D Scatter Plot

A scatter plot is used to display points in three-dimensional space.

Example:

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

import numpy as np

# Data

np.random.seed(0)

x = np.random.rand(50)

y = np.random.rand(50)

z = np.random.rand(50)

# Plot
fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(x, y, z, c='r', marker='o')

# Labels

ax.set_title("3D Scatter Plot")

ax.set_xlabel("X-axis")

ax.set_ylabel("Y-axis")

ax.set_zlabel("Z-axis")

plt.show()

---

Both plots utilize the projection='3d' argument to create the 3D axes and allow visualization in three
dimensions.

2. Explain about various visualization charts like line plots, scatter plots and histograms using Matplotlib
with an example.

1. Line Plot

A line plot is used to display data points connected by straight lines. It's useful for showing trends over
time or continuous data.

import matplotlib.pyplot as plt

# Sample data
x = [0, 1, 2, 3, 4, 5]

y = [0, 1, 4, 9, 16, 25]

# Create a line plot

plt.plot(x, y, marker='o')

# Labels and title

plt.xlabel('X axis')

plt.ylabel('Y axis')

plt.title('Line Plot')

# Show the plot

plt.show()

2. Scatter Plot

A scatter plot is used to display individual data points as dots. It's useful for observing the relationship
between two variables.import matplotlib.pyplot as plt

# Sample data

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

y = [5, 7, 2, 4, 9]

# Create a scatter plot

plt.scatter(x, y, color='r')

# Labels and title

plt.xlabel('X axis')
plt.ylabel('Y axis')

plt.title('Scatter Plot')

# Show the plot

plt.show()

3. Histogram

A histogram is used to represent the distribution of data. It divides data into bins and displays the
frequency of each bin.

import matplotlib.pyplot as plt

# Sample data

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

# Create a histogram

plt.hist(data, bins=5, edgecolor='black')

# Labels and title

plt.xlabel('Value')

plt.ylabel('Frequency')

plt.title('Histogram')

# Show the plot

plt.show()

3. Briefly explain about visualization with Seaborn. Give an example working code segment that
represents a 2D kernel density plot for any data.
Seaborn is a powerful Python visualization library based on Matplotlib that provides a high-level
interface for drawing attractive and informative statistical graphics. Seaborn simplifies the process of
creating complex visualizations and offers various built-in themes and color palettes to make your plots
aesthetically pleasing.

Key Features of Seaborn:

Ease of Use: Simplifies the creation of complex visualizations.

Themes and Color Palettes: Enhances the aesthetics of plots.

Statistical Plots: Provides advanced plot types like violin plots, box plots, and pair plots.

DataFrames Integration: Works seamlessly with Pandas DataFrames.

2D Kernel Density Plot

A kernel density plot is used to estimate the probability density function of a continuous random
variable. A 2D kernel density plot visualizes the joint distribution of two variables.

Example: 2D Kernel Density Plot

import seaborn as sns

import matplotlib.pyplot as plt

import numpy as np

# Generate sample data

np.random.seed(42)

x = np.random.normal(size=100)
y = np.random.normal(size=100)

# Plot 2D Kernel Density

sns.kdeplot(x=x, y=y, cmap="Blues", shade=True, bw_adjust=0.5)

# Add labels and title

plt.title("2D Kernel Density Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.show()

Key Points of the Example:

1. sns.kdeplot:

Creates the 2D kernel density plot.

Parameters:

x and y: Input data.

cmap: Color map for visualization.

shade: Fills the density area with color.

bw_adjust: Bandwidth adjustment for smoothing.

2. Data: The data is randomly generated from a normal distribution for simplicity.

---

Use Case

2D Kernel Density Plots are particularly useful for visualizing joint distributions, such as:

Examining relationships between two continuous variables.

Identifying clusters or regions with high densities in the data.

4. Develop a code snippet that projects our globe as a 2-D flat surface (using cylindrical project) and
convey information about the location of any three major Indian cities I the map(using scatter plot)
import matplotlib.pyplot as plt

from mpl_toolkits.basemap import Basemap

# Initialize the map with a cylindrical projection

plt.figure(figsize=(10, 6))

m = Basemap(projection='cyl', resolution='l', llcrnrlat=-90, urcrnrlat=90,

llcrnrlon=-180, urcrnrlon=180)

# Draw map features

m.drawcoastlines(color='gray')

m.drawcountries(color='black')

m.fillcontinents(color='lightyellow', lake_color='lightblue')

m.drawmapboundary(fill_color='lightblue')

# Locations of three major Indian cities: (longitude, latitude)

cities = {

'New Delhi': (77.1025, 28.7041),

'Mumbai': (72.8777, 19.0760),

'Chennai': (80.2707, 13.0827)

# Plot the cities on the map

for city, (lon, lat) in cities.items():

plt.scatter(lon, lat, latlon=True, s=100, c='red', label=city)

plt.text(lon + 3, lat, city, fontsize=10, color='blue') # Add labels


# Title and legend

plt.title("Major Indian Cities on a Cylindrical Projection Map")

plt.legend(loc='lower left')

# Display the map

plt.show()

---

Explanation:

1. Basemap Setup:

The Basemap object is initialized with a cylindrical projection (projection='cyl'), suitable for global maps.

The llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon define the latitude and longitude bounds.

2. Cities Data:

Three cities (New Delhi, Mumbai, and Chennai) are defined with their respective latitude and longitude.
3. Scatter Plot:

plt.scatter places the cities on the map.

plt.text annotates the cities with their names.

4. Map Features:

Coastlines, country borders, continents, and map boundaries are drawn for clarity.

You might also like