Unit - 2

Data Visualization using Python

Manish Patel

Data Visualization with Python

AREA PLOT

import pandas as pd
import matplotlib.pyplot as plt
# Load market share data from a CSV file
data = pd.read_csv('https://raw.githubusercontent.com/patelmanishv/Sem4Data/main/AXISBANK.csv')
# Convert the 'date' column to a datetime format
data['Date'] = pd.to_datetime(data['Date'])
# Set the 'date' column as the index
data.set_index('Date', inplace=True)
# Create an area plot of market share by company
data.plot(kind='area', stacked=True)
# Add axis labels and a title
plt.xlabel('Date')
plt.ylabel('Market Share')
plt.title('Market Share by Company')
# Show the plot
plt.show()

Plot the high and low share prices as lines

plt.plot(data.index, data['High'], color='blue', label='High')
plt.plot(data.index, data['Low'], color='red', label='Low')
# Shade the area between the high and low share prices
plt.fill_between(data.index, data['High'], data['Low'],
color='grey', alpha=0.2)
# Add axis labels and a title
plt.xlabel('Date')
plt.ylabel('Share Price')
plt.title('Share Prices for XYZ Corporation')
# Add a legend
plt.legend()
# Show the plot
plt.show()

AREA PLOT

import numpy as np
import matplotlib.pyplot as plt
# Create data
x=range(1,6)
y=[1,4,6,8,4]
# Area plot
plt.fill_between(x, y)
plt.show()

AREA PLOT EXAMPLE

import matplotlib.pyplot as plt
import pandas as pd
# create sample data
data = {'Year': [2015, 2016, 2017, 2018, 2019, 2020],
'Sales': [100, 120, 150, 170, 200, 220],
'Expenses': [70, 80, 90, 100, 110, 120]}
df = pd.DataFrame(data)
# create area plot
plt.stackplot(df['Year'], df['Sales'], df['Expenses'],
labels=['Sales', 'Expenses'])
# add labels and legend
plt.xlabel('Year')
plt.ylabel('Amount ($)')
plt.title('Sales and Expenses Over Time')
plt.legend(loc='upper left')
# show plot
plt.show()

FILL BETWEEN PLOT

import matplotlib.pyplot as plt
import pandas as pd
# create sample data
data = {'Year': [2015, 2016, 2017, 2018, 2019, 2020],
'Sales': [100, 70, 150, 170, 200, 220],
'Expenses': [70, 80, 90, 100, 110, 120]}
df = pd.DataFrame(data)
# create fill_between plot
plt.fill_between(df['Year'], df['Sales'], df['Expenses'],
alpha=0.5, label='Sales - Expenses')
# add labels and title
plt.xlabel('Year')
plt.ylabel('Amount ($)')
plt.title('Sales and Expenses Over Time')
plt.legend()
# show plot
plt.show()

FILLBETWEEN LINES

import matplotlib.pyplot as plt
import numpy as np
# generate data
months = np.arange(1, 13)
sales = np.array([10, 15, 20, 30, 20, 50, 30, 70, 80, 40, 100, 10])
expenses = np.array([5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60])
# initialize figure and axis
fig, ax = plt.subplots()
# plot sales as a green line
ax.plot(months, sales, color='green', label='Sales')
# plot expenses as a red line
ax.plot(months, expenses, color='red', label='Expenses')
# shade the area between the two lines where sales > expenses
ax.fill_between(months, sales, expenses, where=sales > expenses,
alpha=0.2, color='blue',interpolate=True)
# shade the area between the two lines where expenses > sales
ax.fill_between(months, sales, expenses, where=expenses > sales,
alpha=0.2, color='yellow',interpolate=True)
# add labels, title, and legend
ax.set_xlabel('Month')
ax.set_ylabel('Amount ($)')
ax.set_title('Sales and Expenses')
ax.legend()
# display the plot
plt.show()
#Sometimes you need to save the graphic automatically. In this case,
#you can save it programmatically using
#the plt.savefig() function, as shown in the following code:
plt.savefig('MySamplePlot.png', format='png')
<Figure size 640x480 with 0 Axes>

BOXPLOT

import matplotlib.pyplot as plt
import numpy as np
# Create some random data
data = [np.random.normal(0, std, 100) for std in range(1, 4)]
#print(data)
# Create a figure and axis object
fig, ax = plt.subplots()
# Create a box plot of the data
ax.boxplot(data)
# Add labels and title
ax.set_xticklabels(['Data 1', 'Data 2', 'Data 3'])
ax.set_ylabel('Value')
ax.set_title('Box plot of data')
plt.show()

BOXPLOT WITH DATAFRAME

df=pd.read_csv("https://raw.githubusercontent.com/patelmanishv/Sem4Data/main/auto-mpg.csv")

#| output: true
import matplotlib.pyplot as plt
import numpy as np
# create a new figure and axis object
fig, ax = plt.subplots()
# plot a boxplot of the 'value' column grouped by the 'category' column
df.boxplot(column=["mpg"],by="cylinders",ax=ax,widths=0.75, notch=False)
ax.set_xticks([1,2,3, 4, 5, 6, 7, 8])
ax.set_yticks([0, 10, 20, 30, 40, 50])
plt.xlabel("cylinders")
plt.ylabel("mpg")
fig.suptitle("box plot",fontsize=8)
plt.show()

SEABORN VISUALIZATION

import seaborn as sns
sns.boxplot(x=df["cylinders"],y=df["mpg"],data=df)
plt.show()

SCATTER PLOT

import matplotlib.pyplot as plt
import numpy as np
# Create some sample data
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = 1000 * np.random.rand(50)
# Create a new figure and axis object
fig, ax = plt.subplots()
# Create a scatter plot of x vs y with colors and sizes
ax.scatter(x, y, c=colors, s=sizes)
# Set the axis labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Scatter Plot Example with Colors and Sizes')
# Show the plot
plt.show()

HEATMAP

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Example dictionary
data_dict = {'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8],
'C': [9, 10, 11, 12],
'D': [13, 14, 15, 16]}
# Convert dictionary to data frame
df = pd.DataFrame(data_dict)
# Create heat map using Seaborn
sns.heatmap(df, cmap='coolwarm',annot=True)
# Show plot
plt.show()

HEATMAP EXAMPLE

# importing the modules
import numpy as np
import seaborn as sn
import matplotlib.pyplot as plt
# generating 2-D 10x10 matrix of random numbers
# from 1 to 100
data = np.random.randint(low = 1,
high = 100,
size = (10, 10))
print("The data to be plotted:\n")
print(data)
# plotting the heatmap
hm = sn.heatmap(data = data)
# displaying the plotted heatmap
plt.show()
The data to be plotted:

[[69 17 58 23 83 81 46 11 44 40]
 [ 1 31 41 65 25 30  7 21 97 22]
 [20 10 42 54 44 30 63 93 45 67]
 [79 58 45 29 58 12 20 13 41 46]
 [67  8 38  8 48 21  3 16 82 92]
 [85 48 43 27 28 94 86 45 40 84]
 [59 62 97 12 37 71 86 10 88  8]
 [45 94 37 59 19 83 13 20 38 67]
 [87 46  3 34 83  3  4 89 23 82]
 [35 57 94 94 98 78 70  3 41  3]]

WAFFLE CHART

# !pip install pywaffle
import pandas as pd
import matplotlib.pyplot as plt
from pywaffle import Waffle
# creation of a dataframe
data ={'phone': ['Xiaomi', 'Samsung',
'Apple', 'Nokia', 'Realme'],
'stock': [44, 12, 8, 5, 50]
}
df = pd.DataFrame(data)
# To plot the waffle Chart
fig = plt.figure(
FigureClass = Waffle,
rows = 10,
values = df.stock,
labels = list(df.phone)
)

WAFFLECHART EXAMPLE

from pywaffle import Waffle
import matplotlib.pyplot as plt
# Data
value = [12, 22, 16, 38, 12]
# Waffle chart
plt.figure(
FigureClass = Waffle,
rows = 10,
columns = 10,
values = value,
characters = '♥')
plt.show()

REGRESSION PLOT

import seaborn as sns
# Example data
x = [1, 2, 3, 4, 5, 6]
y = [3, 5, 7, 8, 10, 12]
# Create regression plot with customization
sns.regplot(x=x, y=y, color='green', marker='o',
scatter_kws={'s': 100}, line_kws={'lw': 2})
# Set plot title
plt.title('Regression Plot')
# Show plot
plt.show()

REGPLOT

df=pd.read_csv("https://raw.githubusercontent.com/patelmanishv/Sem4Data/main/auto-mpg.csv")
plt.figure(figsize=(15, 10))
sns.set(font_scale=1.5)
ax = sns.regplot(x='mpg', y='acceleration', data = df,
color='green', marker = '+',
scatter_kws={'s': 200})
ax.set(xlabel='mpg', ylabel='acceleration') # add x- and y-labels
ax.set_title('mpg vs acceleration') # add title
plt.show()

CORRELATION

import pandas as pd

# Select only numeric columns (excluding non-numeric columns)
numeric_columns = df.select_dtypes(include=["float64", "int64"])

# Compute correlations
correlation_matrix = numeric_columns.corr(method="pearson")

# Print the correlation matrix
print(correlation_matrix)
                   mpg  cylinders  displacement    weight  acceleration  \
mpg           1.000000  -0.775396     -0.804203 -0.831741      0.420289   
cylinders    -0.775396   1.000000      0.950721  0.896017     -0.505419   
displacement -0.804203   0.950721      1.000000  0.932824     -0.543684   
weight       -0.831741   0.896017      0.932824  1.000000     -0.417457   
acceleration  0.420289  -0.505419     -0.543684 -0.417457      1.000000   
model year    0.579267  -0.348746     -0.370164 -0.306564      0.288137   
origin        0.563450  -0.562543     -0.609409 -0.581024      0.205873   

              model year    origin  
mpg             0.579267  0.563450  
cylinders      -0.348746 -0.562543  
displacement   -0.370164 -0.609409  
weight         -0.306564 -0.581024  
acceleration    0.288137  0.205873  
model year      1.000000  0.180662  
origin          0.180662  1.000000  

WORDCLOUDS

# !pip install wordcloud
import requests
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
# Download the text file
url = "https://www.gutenberg.org/files/11/11-0.txt"
response = requests.get(url)
text = response.text
stopwords = set(STOPWORDS)

CREATE WORD CLOUD

# instantiate a word cloud object
alice_wc = WordCloud(
background_color='white',
max_words=2000,
stopwords=stopwords
)
# generate the word cloud
alice_wc.generate(text)
<wordcloud.wordcloud.WordCloud at 0x1592545fa10>

DISPLAY

# display the word cloud
import matplotlib.pyplot as plt
plt.imshow(alice_wc)
plt.axis('off')
plt.show()

ADD STOP WORDS

stopwords.add('said') # add the words said to stopwords
# re-generate the word cloud
alice_wc.generate(text)
# display the cloud
fig = plt.figure(figsize=(14, 18))
plt.imshow(alice_wc)
plt.axis('off')
plt.show()

FOLIUM - GEOSPATIAL PYTHON

# !pip install folium
import folium
mapObj = folium.Map(location=[23.437730075416685, 72.585859375],
zoom_start=10, tiles='OpenStreetMap')
mapObj

LAYER CONTROLS

import folium
mapObj = folium.Map()
# add layers control over the map
folium.LayerControl().add_to(mapObj)
mapObj

ADD LAYERS


m2=folium.Map(location=[28.644800, 77.216721])
folium.TileLayer('cartodbpositron').add_to(m2)
folium.TileLayer('cartodbdark_matter').add_to(m2)
folium.LayerControl().add_to(m2)
m2

Save map

mapObj.save('Mymap.html')

INDIAN STATES

import folium
mapObj = folium.Map(location=[23.437730075416685, 72.585859375],
zoom_start=5)
layer1 = folium.GeoJson(
data=(open("Indian_States.geojson", 'r').read()),
name="India")
layer1.add_to(mapObj)
mapObj

BORDER AND STYLE CONTROL

import folium
mapObj = folium.Map(location=[23.437730075416685, 72.585859375],
zoom_start=5)
# style options - https://leafletjs.com/reference-1.7.1.html#path
bordersStyle = {
'color': 'green',
'weight': 2,
'fillColor': 'blue',
'fillOpacity': 0.2
}
folium.GeoJson(
data=(open("Indian_States.geojson", 'r').read()),
name="India",
style_function=lambda x: bordersStyle).add_to(mapObj)
# mapObj.save('output2.html')
mapObj

CIRCLE

import folium
mapObj = folium.Map(location=[23.437730075416685, 72.585859375],
zoom_start=6)
folium.Circle(location=[23.294059708387206, 78.26660156250001],
radius=50000).add_to(mapObj)
# mapObj.save('output.html')
mapObj

PARAMETERS


import folium
mapObj = folium.Map(location=[23.437730075416685, 72.585859375],
zoom_start=6)
folium.Circle(location=[23.437730075416685, 72.585859375],
radius=50000,
color='green',
weight=6,
fill_color='red',
fill_opacity = 0.5).add_to(mapObj)
# mapObj.save('output.html')
mapObj

CIRCLE MARKER


import folium
mapObj = folium.Map(location=[23.437730075416685, 72.585859375],
zoom_start=6)
folium.CircleMarker(location=[23.437730075416685, 72.585859375],
radius=50
).add_to(mapObj)
# mapObj.save('output.html')
mapObj

TOOLTIP AND POPUP


import folium
mapObj = folium.Map(location=[23.437730075416685, 72.585859375],
zoom_start=6)
folium.Circle(location=[23.437730075416685, 72.585859375],
radius=50000,
fill=True,
tooltip="This is a tooltip text",
popup=folium.Popup("""<h2>This is a popup</h2><br/>
This is a <b>new line</b><br/>
<a href='https://www.ljku.edu.in'> hi</a>""", max_width=500)
).add_to(mapObj)
# mapObj.save('output.html')
mapObj

LAYERS SHAPE


from os import name
import folium
mapObj = folium.Map(location=[23.437730075416685, 72.585859375],
zoom_start=6)
# create a layer on the map object
shapesLayer = folium.FeatureGroup(name="circles").add_to(mapObj)
folium.Circle(location=[23.437730075416685, 72.585859375],
radius=50000,
fill=True).add_to(shapesLayer)
folium.LayerControl().add_to(mapObj)
# mapObj.save('output.html')
mapObj

CONCISE EXAMPLE

import folium
mapObj = folium.Map(location=[23.437730075416685, 72.585859375],
zoom_start=6)
shapesLayer = folium.FeatureGroup(name="circles").add_to(mapObj)
circlesData = [
[25, 74, 80000],
[22, 79, 60000],
[26, 82, 90000]
]
for cData in circlesData:
    folium.Circle(location=[cData[0], cData[1]],
        radius=cData[2],
        weight=5,
        color='green',
        fill_color='red',
        tooltip="Tooltip text",
        popup=folium.Popup("""<h2>This is a popup</h2><br/>
        This is a <b>new line</b><br/>
        <a href='https://www.ljku.edu.in'> hi</a>""",
        max_width=500)
        ).add_to(shapesLayer)
folium.LayerControl().add_to(mapObj)
# mapObj.save('output.html')
mapObj

FEATURE GROUP


import folium
# Create a map object
m = folium.Map(location=[45.5236, -122.6750], zoom_start=13)
# Create a FeatureGroup object
fg = folium.FeatureGroup(name="My Feature Group")
# Add a marker to the FeatureGroup
folium.Marker(location=[45.5236, -122.6750],
popup="Portland, OR").add_to(fg)
# Add the FeatureGroup to the map
fg.add_to(m)
# Display the map
m

FEATURE MARKER


import folium
# Create a map object centered on San Francisco
m = folium.Map(location=[37.7749, -122.4194], zoom_start=13)
# Create a marker object with a popup message
marker = folium.features.Marker(location=[37.7749, -122.4194],
popup='This is San Francisco!')
# Add the marker to the map
marker.add_to(m)
# Display the map
m

MARKER


import folium
# Create a map object centered on San Francisco
m = folium.Map(location=[37.7749, -122.4194], zoom_start=13)
# Create an icon object with an image file
icon = folium.features.Icon(icon='cloud')
# Create a marker object with the custom icon and a popup message
marker = folium.Marker(location=[37.7749, -122.4194],
popup='This is San Francisco!', icon=icon)
# Add the marker to the map
marker.add_to(m)
# Display the map
m

POLYLINE

import folium
# Create a map object centered on San Francisco
m = folium.Map(location=[37.7749, -122.4194], zoom_start=13)
# Define the coordinates of the polygon
coords = [[37.7833, -122.4214], [37.7864, -122.4092],
[37.7764, -122.4083], [37.7733, -122.4206]]
# Create a polygon object with the polygon coordinates
f=folium.features.PolyLine(locations=coords,
color='green', fill_color='green')
# Add the polygon to the map
f.add_to(m)
# Display the map
m

ADD CHILD

import folium
m = folium.Map(location=[37.7749, -122.4194], zoom_start=13)
marker = folium.Marker(location=[37.7749, -122.4194])
#Then, we can add this marker to the map using the add_child() method:
m.add_child(marker)
m

INCIDENT ANALYSIS

df_incidents = pd.read_csv("Police_Department_Incidents_-_Previous_Year__2016_.csv")
# df_incidents.head()
# df_incidents.shape
# get the first 100 crimes in the df_incidents dataframe
limit = 100
df_incidents = df_incidents.iloc[0:limit, :]
df_incidents.shape

SAN FRANCISCO MAP

# San Francisco latitude and longitude values
latitude = 37.77
longitude = -122.42
sanfran = folium.Map(location=[latitude, longitude], zoom_start=13)
sanfran

SAN FRANCISCO MAP

ADD FEATURE GROUP

# instantiate a feature group for the incidents in the dataframe
incidents = folium.map.FeatureGroup()
# loop through the 100 crimes and add each to the incidents feature group
for lat, lng, in zip(df_incidents.Y, df_incidents.X):
    incidents.add_child(
        folium.features.CircleMarker(
            [lat, lng],
            radius=5, # define how big you want the circle markers to be
            color='yellow',
            fill=True,
            fill_color='blue',
            fill_opacity=0.6
        )
    )
# add incidents to map
sanfran.add_child(incidents)

CHOROPLETH MAPS


usa_state = folium.Map(location=[48, -102], zoom_start=3)
folium.Choropleth(
geo_data = 'https://raw.githubusercontent.com/patelmanishv/Sem4Data/main/us-states.json', #json
name ='choropleth',
data = pd.read_csv("https://raw.githubusercontent.com/patelmanishv/Sem4Data/main/US_Unemployment_Oct2012.csv"),
columns = ['State', 'Unemployment'], #columns to work on
key_on ='feature.id',
fill_color ='YlGnBu', #I passed colors Yellow,Green,Blue
fill_opacity = 0.7,
line_opacity = 0.2,
legend_name = "Unemployment scale").add_to(usa_state)
usa_state

NETWORKX

import networkx as nx
import matplotlib.pyplot as plt
# Create a graph
G = nx.Graph()
# Add nodes to the graph
G.add_node(1)
G.add_node(2)
G.add_node(3)
# Add edges to the graph
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
# Draw the graph
nx.draw(G, with_labels=True)
plt.show()

A BASIC EXAMPLE

import networkx as nx
import matplotlib.pyplot as plt
# Create an empty undirected graph
G = nx.Graph()
# Add nodes to the graph
G.add_nodes_from(['A', 'B', 'C'])
# Add edges to the graph
G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'C')])
# Draw the graph
nx.draw(G, with_labels=True)
plt.show()

GRAPH EXAMPLE

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_node(1)
G.add_nodes_from([2, 3])
G.add_nodes_from(range(4, 7))
G.add_edge(1, 2)
G.add_edge(1, 1)
G.add_edges_from([(2,3), (3,6), (4,6), (5,6)])
nx.draw_networkx(G, node_size=850, node_color='red',
width=5, edge_color='blue')
plt.show()

DIGRAPH

import networkx as nx
import matplotlib.pyplot as plt
# Create an empty directed graph
G = nx.DiGraph()
# Add nodes to the graph
G.add_nodes_from(['A', 'B', 'C', 'D'])
# Add edges to the graph
G.add_edges_from([('A', 'B'), ('A', 'C'), ('A', 'D'),
('C', 'D'), ('D', 'C')])
# Draw the graph
nx.draw(G, with_labels=True)
plt.show()

DIGRAPH EXAMPLE

import networkx as nx
import matplotlib.pyplot as plt
g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)
nx.draw(g,with_labels=True, node_size=1000, node_color='red',
width=5, edge_color='blue')
plt.draw()
plt.show()

ADJACENCY MATRIX

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Define the adjacency matrix
adj_matrix = np.array([[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]])
# Create a directed graph from the adjacency matrix
G = nx.DiGraph(adj_matrix)
# Draw the graph
nx.draw(G, with_labels=True)
plt.show()

import networkx as nx
import matplotlib.pyplot as plt
g = nx.DiGraph()
L = [[1,0,0,1,0,1,1],[0,1,1,1,1,1,0],[1,1,1,0,1,0,1],[1,0,0,0,1,0,1],
[1,1,1,0,0,0,1],[1,1,1,1,1,0,1], [0,1,1,0,0,0,1]]
g = nx.DiGraph()
g.add_nodes_from([0,1,2,3,4,5,6])
for i in range(0,7):
    for j in range(0,7):
        if L[i][j] == 1:
            g.add_edge(i,j)
nx.draw(g, with_labels=True, node_size=1000, node_color='red',
width=2, edge_color='blue')
plt.show()

import networkx as nx
import matplotlib.pyplot as plt
L= np.array([[1,0,0,1,0,1,1],[0,1,1,1,1,1,0],[1,1,1,0,1,0,1],
[1,0,0,0,1,0,1],[1,1,1,0,0,0,1],
[1,1,1,1,1,0,1], [0,1,1,0,0,0,1]])
g = nx.DiGraph(L)
g.add_nodes_from([0,1,2,3,4,5,6])
nx.draw(g, with_labels=True, node_size=1000, node_color='red', width=2)
plt.show()

The following dictionary shows how five people follow each other on Instagram

instagram = {‘person1’: [0,1,1,0,1], ‘person2’: [0,0,1,0,1], ‘person3’: [1,1,0,1,1],‘person4’: [1,1,1,0,0], ‘person5’: [1,1,0,0,0]} E.g., the list for person1 has the value on index 2 as 1 which means person1 followsperson3 and a directed edge should be added from person1 to person3. Using networkx library, create a directed graph. To create a directed graph from the instagram dictionary using networkx, we can follow these steps: Import the networkx and matplotlib packages. Create an empty directed graph using the DiGraph() class. Add nodes to the graph using the add_nodes_from() method

import networkx as nx
import matplotlib.pyplot as plt
instagram = {
'person1': [0,1,1,0,1],
'person2': [0,0,1,0,1],
'person3': [1,1,0,1,1],
'person4': [1,1,1,0,0],
'person5': [1,1,0,0,0]}
# Create an empty directed graph
G = nx.DiGraph()
# Add nodes to the graph
G.add_nodes_from(instagram.keys())
# Add edges to the graph
for i, follower in enumerate(instagram):
    for j, follows in enumerate(instagram[follower]):
        if follows:
            G.add_edge(follower, list(instagram.keys())[j])
# Draw the graph
nx.draw(G, with_labels=True)
plt.show()

You have been hired as a network analyst by a company to analyze the social network of their employees. The company has provided you with the following data: There are 5 employees in the company, each idenfied by a unique ID from 1 to 5. The following relaonships exist between the employees:

  1. Employee 1 is friends with Employee 2 and Employee 3.
  2. Employee 2 is friends with Employee 4.
  3. Employee 3 is friends with Employee 5. Your task is to create a NetworkX graph representing this social network and display it

import matplotlib.pyplot as plt
import networkx as nx

# Create an empty undirected graph
G = nx.Graph()
# Add nodes to the graph
G.add_nodes_from([1, 2, 3, 4, 5])
# Add edges to the graph
G.add_edge(1, 2)
G.add_edge(1, 3)
G.add_edge(2, 4)
G.add_edge(3, 5)
# Set the node labels
labels = {1: 'Employee 1', 2: 'Employee 2', 3: 'Employee 3',
4: 'Employee 4', 5: 'Employee 5'}
# Draw the graph with node labels
nx.draw(G, labels=labels, with_labels=True)
plt.show()