0% found this document useful (0 votes)
7 views9 pages

Data Science Lab Part 2

The document provides an overview of visualizing geographic data using the Basemap toolkit in Python, highlighting its installation and basic usage for creating map visualizations. It also explains how to convert a Python list to a byte array and vice versa using the struct module, along with a detailed algorithm and example code. Additionally, it describes how to display multiple types of charts using the matplotlib package, including line charts, bar charts, scatter plots, and histograms.

Uploaded by

elza
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)
7 views9 pages

Data Science Lab Part 2

The document provides an overview of visualizing geographic data using the Basemap toolkit in Python, highlighting its installation and basic usage for creating map visualizations. It also explains how to convert a Python list to a byte array and vice versa using the struct module, along with a detailed algorithm and example code. Additionally, it describes how to display multiple types of charts using the matplotlib package, including line charts, bar charts, scatter plots, and histograms.

Uploaded by

elza
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/ 9

Visualizing Geographic Data with Basemap

Aim:
To Visualizing Geographic Data with Basemap

One common type of visualization in data science is that of geographic data. Matplotlib's
main tool for this type of visualization is the Basemap toolkit, which is one of several Matplotlib
toolkits which lives under the mpl_toolkits namespace. Admittedly, Basemap feels a bit clunky
to use, and often even simple visualizations take much longer to render than you might hope.
More modern solutions such as leaflet or the Google Maps API may be a better choice for more
intensive map visualizations. Still, Basemap is a useful tool for Python users to have in their
virtual toolbelts. In this section, we'll show several examples of the type of map visualization
that is possible with this toolkit.

Installation of Basemap is straightforward; if you're using conda you can type this and the
package will be downloaded:

conda install basemap

Code:

fig = plt.figure(figsize=(8, 8))

m = Basemap(projection='lcc',

resolution=None,

width=8E6, height=8E6,

lat_0=45, lon_0=-100,)
m.etopo(scale=0.5, alpha=0.5)

# Map (long, lat) to

(x,y) for plotting x, y =

m(-122.3, 47.6)

plt.plot(x, y, 'ok',markersize=5)

plt.text(x, y, ' Seattle',

fontsize=12);
from mpl_toolkits.basemap
import Basemap
import matplotlib.pyplot as
pltfig = plt.figure(figsize =
(12,12)) m =
Basemap()
m.drawcoastlines()
m.drawcoastlines(linewidth=1.0,

linestyle='dashed', color='red')

plt.title("Coastlines", fontsize=20)
plt.show()

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import seaborn as sns


import geopandas as gpd
import shapefile as shp
from
shapely.geometry

import Point sns.set_style('whitegrid')

fp = r'Maps_with_python\india-polygon.shp' map_df =gpd.read_file(fp)


map_df_copy = gpd.read_file(fp)
plt.plot(map_df , markersize=5)
Result :

Thus the program using Basemap was installed and successfully

executed geographic visualization.


PYTHON PROGRAM TO COVERT TO AN ARRAY OF MACHINE
VALUES AND VICE VERSA

AIM

To convert a Python list to an array of machine values (also known as a "byte array" or "packed
binary data") and vice versa, you can use the structmodule. This module helps in packing and
unpacking Python values into C structs, which are represented as Python bytes objects.

Here’s a simple program that demonstrates how to achieve


this:

Algorithm
:

Step-by-Step Algorithm

1. Define Function to Convert List to Machine Values:


o Input: A list of floating-point numbers (input_list).
o Process:
Determine the format string for packing the data using the length of the list and
the data type ('f' for 4-byte float).
Use struct.pack()to convert the list into a byte array using the determined
format string.
o Output: Byte array (machine_values) representing the list in machine values.
2. Define Function to Convert Machine Values Back to List:
o Input: A byte array (machine_values).
o Process:
Calculate the number of floats in the byte array by dividing its length by the size
of one float (struct.calcsize('f')).
Use struct.unpack()to convert the byte array back to a tuple of floats.
Convert the tuple to a list.
o Output: The original list of floats.
3. Example Usage:
o Step 1: Define an example list of floats, input_list.
o Step 2: Call list_to_machine_values()to convert the list to machine values and
print the result.
o Step 3: Call machine_values_to_list()to convert the machine values back to a list
and print the result.

Detailed Algorithm Breakdown

1. Convert List to Machine Values (list_to_machine_values):


o Input: input_list= [1.5, 2.5, 3.5, 4.5].
o Determine Format String: format_string = '4f'(for 4 floats).
o Packing:
machine_values = struct.pack('4f', 1.5, 2.5, 3.5, 4.5).
The result is a byte array that represents these floating-point numbers
in a machine-readable format.
o Output: A byte array, e.g., b'\x00\x00\xc0?\x00\x00
@\x00\x00@\x00\x00\x90@'`.
2. Convert Machine Values to List (machine_values_to_list):
o Input: machine_values(byte array from the previous step).
o Calculate Number of Floats: number_of_floats = len(machine_values) //
struct.calcsize('f') = 4.
o Unpacking:
unpacked_list = struct.unpack('4f', machine_values).
The result is a tuple, e.g., (1.5, 2.5, 3.5,
4.5).
o Convert to List: Convert the tuple to a list: [1.5, 2.5, 3.5, 4.5].
o Output: The original list of floats.
3. Example Execution:
o Original List: [1.5, 2.5, 3.5, 4.5].
o Machine Values (Byte Array): b'\x00\x00\xc0?\x00\x00
@\x00\x00@\x00\x00\x90@'`.
o Converted Back to List: [1.5, 2.5, 3.5, 4.5].

Explanation:

1. Packing the List:


o The struct.pack() function is used to convert the list of floats into a byte
array (machine values). The format string 'f'is used for each float in the
list. You can change the format according to the data type you are working
with ('i'for integers, 'd' for doubles, etc.).
2. Unpacking the Byte Array:
o The struct.unpack() function is used to convert the byte array back into
a list of Python floats. The number of elements in the byte array is
calculated based on the total byte size and the size of each float
(struct.calcsize('f')).

Adjusting for Different Data Types:

If your input list contains integers, use 'i'in the format

string. For doubles (8-byte floats), use 'd'

Python Program to Convert List to Array of Machine Values and Vice Versa

import struct

def list_to_machine_values(input_list):
# 'f' format character indicates that we're using 4-byte float values
# Adjust the format according to the data type in your list ('i' for
int,
'd' for double, etc.)
format_string = f'{len(input_list)}f'

# Convert the list to machine values (bytes)


machine_values = struct.pack(format_string,
*input_list) return machine_values

def machine_values_to_list(machine_values):
# Calculate the number of floats in the byte array
number_of_floats = len(machine_values) // struct.calcsize('f')

# Unpack the byte array back to a list of floats


unpacked_list = struct.unpack(f'{number_of_floats}f', machine_values)
return list(unpacked_list)

# Example usage
input_list = [1.5, 2.5, 3.5, 4.5]
print("Original list:", input_list)

# Convert list to array of machine values


machine_values = list_to_machine_values(input_list)
print("Machine values (byte array):",
machine_values)

# Convert machine values back to list


output_list = machine_values_to_list(machine_values)
print("Converted back to list:", output_list)

Sample Output

When you run this code, you should get an output similar to:

Original list: [1.5, 2.5, 3.5, 4.5]


Machine values (byte array): b'\x00\x00\xc0?\x00\x00
\x40\x00\x00`@\x00\x00\x90@'
Converted back to list: [1.5, 2.5, 3.5, 4.5]

Explanation of the Output

1. Original List: The original Python list of floats [1.5, 2.5, 3.5, 4.5].
2. Machine Values (Byte Array): The packed byte array (a sequence of
bytes) that represents the list of floats in memory.
3. Converted Back to List: The unpacked list after converting back from the byte
array, matching the original input.

RESULT:

Thus the progam to convert a Python list to an array of machine values computation for
was successfully completed.
PYTHON PROGRAM TO DISPLAY MULTIPLE TYPES OF
CHATS USING MATPOTLIB PACKAGE

AIM:

To display multiple types of charts using the matplotlib package in Python, we


can use various plotting functions such as plot(), bar(), scatter(), and hist()to create
different types of visualizations.

ALGORITHM:

1. Import Necessary Libraries:


o Import the matplotlib.pyplot module as plt for plotting.
o Import numpyas np for generating example data.
2. Generate Example Data:
o Create an array x with values ranging from 1 to 10 using np.arange(1, 11).
o Generate a random integer array y of size 10 with values between 1 and 20
using
np.random.randint(1, 20, size=10).
o Generate another random integer array zof size 10 with values between 1 and
100 using np.random.randint(1, 100, size=10).
3. Create Figure and Subplots:
o Use plt.subplots(2, 2, figsize=(10, 8)) to create a figure (fig) and a
2x2 grid of subplots (axs), with each subplot occupying one cell in the grid.
o The figure size is set to 10x8 inches.
4. Plot the Line Chart:
o Use axs[0, 0].plot(x, y, marker='o', linestyle='-',
color='b', label='Line Chart') to create a line chart on the first
subplot (axs[0, 0]).
o Set the title, x-axis label, and y-axis label using set_title(),
set_xlabel(), and set_ylabel()methods, respectively.
o Add a legend to the subplot using axs[0, 0].legend().
5. Plot the Bar Chart:
o Use axs[0, 1].bar(x, y, color='g', label='Bar Chart') to create a
bar chart on the second subplot (axs[0, 1]).
o Set the title, x-axis label, and y-axis label using set_title(),
set_xlabel(), and set_ylabel()methods, respectively.
o Add a legend to the subplot using axs[0, 1].legend().
6. Plot the Scatter Plot:
o Use axs[1, 0].scatter(x, z, color='r', label='Scatter
Plot') to create a scatter plot on the third subplot (axs[1, 0]).
o Set the title, x-axis label, and y-axis label using set_title(), set_xlabel(),
and set_ylabel()methods, respectively.
o Add a legend to the subplot using axs[1, 0].legend().
7. Plot the Histogram:
o Use axs[1, 1].hist(z, bins=5, color='m', edgecolor='black',
label='Histogram') to create a histogram on the fourth subplot (axs[1,
1]).
o Set the title, x-axis label, and y-axis label using set_title(),
set_xlabel(), and set_ylabel()methods, respectively.
o Add a legend to the subplot using axs[1, 1].legend().
8. Adjust Layout:
o Use plt.tight_layout() to automatically adjust the layout of the subplots
to ensure they do not overlap and have proper spacing.
9. Display the Plots:
o Use plt.show() to display the figure containing all four plots in a 2x2
grid layout.

Below is a Python program that demonstrates how to create a line chart, bar chart, scatter
plot, and histogram using matplotlib.

Python Program to Display Multiple Types of Charts


python
Copy code
import matplotlib.pyplot as plt
import numpy as np

# Example data
x = np.arange(1, 11)
y = np.random.randint(1, 20, size=10)
z = np.random.randint(1, 100, size=10)

# Create a figure and multiple subplots


fig, axs = plt.subplots(2, 2, figsize=(10, 8))

# Line Chart
axs[0, 0].plot(x, y, marker='o', linestyle='-', color='b', label='Line
Chart')
axs[0, 0].set_title('Line Chart')
axs[0, 0].set_xlabel('X-axis')
axs[0, 0].set_ylabel('Y-axis')
axs[0, 0].legend()

# Bar Chart
axs[0, 1].bar(x, y, color='g', label='Bar Chart')
axs[0, 1].set_title('Bar Chart')
axs[0, 1].set_xlabel('Categories')
axs[0, 1].set_ylabel('Values')
axs[0, 1].legend()

# Scatter Plot
axs[1, 0].scatter(x, z, color='r', label='Scatter Plot')
axs[1, 0].set_title('Scatter Plot')
axs[1, 0].set_xlabel('X-axis')
axs[1, 0].set_ylabel('Random Values')
axs[1, 0].legend()

# Histogram
axs[1, 1].hist(z, bins=5, color='m', edgecolor='black', label='Histogram')
axs[1, 1].set_title('Histogram')
axs[1, 1].set_xlabel('Bins') axs[1,
1].set_ylabel('Frequency') axs[1, 1].legend()

# Adjust layout plt.tight_layout()

# Display the plots plt.show()

Explanation

1. Importing Libraries:
o matplotlib.pyplot is imported for plotting various types of charts.
o numpyis used to generate example data.
2. Creating Data:
o xrepresents the X-axis values from 1 to 10.
o yis an array of random integers (for the line chart and bar chart).
o zis another array of random integers (for the scatter plot and histogram).
3. Creating Subplots:
o plt.subplots(2, 2, figsize=(10, 8)) creates a 2x2 grid of subplots with a specific figure
size.
4. Plotting Different Charts:
o Line Chart: plot()function is used with markers, linestyle, and color.
o Bar Chart: bar()function creates a bar chart.
o Scatter Plot: scatter() function creates a scatter plot.
o Histogram: hist()function creates a histogram with specified bins.
5. Customization and Display:
o Titles, labels, and legends are added to each subplot for clarity.
o plt.tight_layout() adjusts the subplots to prevent overlap.
o plt.show() displays the created plots.

Output

When you run the program, it will display a window with four different types of charts arranged in a 2x2 grid:

1. Line Chart (top-left)


2. Bar Chart (top-right)
3. Scatter Plot (bottom-left)
4. Histogram (bottom-right)

RESULT:

Thus the progam to convert a Python list to an array of machine values computation for was successfully
completed

You might also like