[go: up one dir, main page]

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

Lab Py

PYTHON PROGRAMS

Uploaded by

ayushngowda838
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)
26 views9 pages

Lab Py

PYTHON PROGRAMS

Uploaded by

ayushngowda838
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

1A.

BAR PLOT

import matplotlib.pyplot as plt


fruits =['apples','bananas','cherries','Dates']
sales = [20,35,30, 10]
plt.bar (fruits, sales, color = 'blue')
plt.title('fruits sales in a week')
plt.xlabel ('fruits')
plt.ylabel ('no_of_sold')
plt.grid (axis='y')
plt.show ()

1B.SCATTER PLOT

import matplotlib.pyplot as plt


hours_studied=[1,2,3,4,5,6,7]
test_scores=[35, 50, 65, 20, 25, 38, 40]
plt.scatter(hours_studied,test_scores, color = 'orange')
plt.title("hours studied vs test scores")
plt.xlabel('Hours studied')
plt.ylabel('Test scores')
plt.grid()
plt.show()
2A.HISTOGRAM PLOT

import matplotlib.pyplot as plt


import numpy as np
Ages=[22,28,34,39,45,50,70,65,90,20]
plt.hist(Ages,bins=10,color='blue',edgecolor='black')
plt.title ('Ages distribution of a group of people')
plt.xlabel('Ages')
plt.ylabel('Frequemy')
plt.grid(axis='y')
plt.show()

2B.PYE CHART

import matplotlib.pyplot as plt

brands = ['Apple', 'Samsung', 'MI', 'Other']


market_share = [30, 50, 10, 10]
colors = ['#ff9999', '#66b3ff', '#49ff99', '#ffc199'] # Fixed color list length

plt.figure(figsize=(8, 8)) # Corrected the figure size


plt.pie(market_share, labels=brands, autopct='%1.1f%%',
startangle=140, colors=colors) # Fixed labels parameter

plt.title("Smartphone Market Share")


plt.axis('equal') # Ensures that the pie chart is circular
plt.show()
3A.LINEAR PLOT
import numpy as np
import matplotlib.pyplot as plt

# Parameters for the line


m = 2
b = 1

# Generate x values
x = np.linspace(-10, 10, 100)
# Calculate y values
y = m * x + b

# Create the plot


plt.figure(figsize=(10, 6))
plt.plot(x, y, label=f'y = {m}x + {b}', color='blue')

# Add title and labels


plt.title('Linear plot: y = mx + b')
plt.xlabel('x values')
plt.ylabel('y values')

# Add gridlines and axis lines


plt.axhline(0, color='black', linewidth=0.5, linestyle='--')
plt.axvline(0, color='black', linewidth=0.5, linestyle='--')

# Show the grid


plt.grid(color='gray', linestyle='--', linewidth=0.5)

# Add legend
plt.legend()

# Set the limits for x and y axes


plt.xlim(-10, 10)
plt.ylim(-20, 20)

# Show the plot


plt.show()
3B.STACK & SUBPLOT
import numpy as np
import matplotlib.pyplot as plt

# Generate x values from 0 to 10


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

# Calculate y values for sin, cos, and tan


y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# Clip tan values to avoid very large values


y3 = np.clip(y3, -10, 10)

# Create subplots (3 rows, 1 column)


fig, axs = plt.subplots(nrows=3, ncols=1, figsize=(8, 10))

# Plot sin(x)
axs[0].plot(x, y1, color="blue", label='y = sin(x)')
axs[0].set_title('Sin Function')
axs[0].set_ylabel('sin(x)')
axs[0].grid(True)
axs[0].legend()

# Plot cos(x)
axs[1].plot(x, y2, color='orange', label='y = cos(x)')
axs[1].set_title('Cosine Function')
axs[1].set_ylabel('cos(x)')
axs[1].grid(True)
axs[1].legend()

# Plot tan(x)
axs[2].plot(x, y3, color='green', label='y = tan(x)')
axs[2].set_title('Tan Function')
axs[2].set_ylim(-10, 10) # Limit the y-axis for better visualization
axs[2].grid(True)
axs[2].legend()

# Set common x-axis label


plt.xlabel('x values')

# Adjust layout to prevent overlap


plt.tight_layout()

# Show the plot


plt.show()
4.SEA BORN
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# Correcting the dictionary syntax


data = {'pl': ['py', 'Java', 'C++'], 'No_of_users': [55, 40, 5]}

# Creating the DataFrame


df = pd.DataFrame(data)

# Setting the theme for the plot


sns.set_theme(style="whitegrid")

# Creating the barplot


plt.figure(figsize=(10, 6))
axis = sns.barplot(x="pl", y="No_of_users", data=df, palette="deep")

# Customizing the plot


plt.yticks(fontsize=10)
plt.title('Programing language Popularity Among Students', fontsize=16, color='blue')
plt.xlabel("Programming Language", fontsize=16)
plt.ylabel("Number of Users", fontsize=14)

# Display the plot


plt.show()
5A.BOKEH LINE
from bokeh.plotting import figure,show
from bokeh.models import Label,Legend
days=[1,2,3,4,5]
temp_bengaluru=[18,20,22,19,17]
temp_mysuru=[22,25,20,26,23]
plot=figure(title="Temperature
comparision",x_axis_label="Days",y_axis_label="Temperature(C)")
line_mysuru=plot.line(days,temp_mysuru,line_width=2,line_color="blue")
line_bengaluru=plot.line(days,temp_bengaluru,line_width=2,line_color="green")
annotation_mysuru=Label(x=4,y=22,text="Weather in
Mysuru",text_font_size="10pt",text_color="blue")
plot.add_layout(annotation_mysuru)
annotation_bengaluru=Label(x=4,y=20,text="Weather in
Bengaluru",text_font_size="10pt",text_color="green")
plot.add_layout(annotation_bengaluru)
legend=Legend(items=[("Mysuru",[line_mysuru]),("Bengaluru",[line_bengaluru])],
location="top_left")
plot.add_layout(legend)
show(plot)
5B.BOKEH
from bokeh.io import output_file as OF
from bokeh.io import show
from bokeh.layouts import row
from bokeh.plotting import figure as figs
from bokeh.models import HoverTool
fig1=figs(width=400,height=400,title="plot1")
x1=[2,3,5,6]
y1=[1,4,4,7]
fig1.line(x1,y1,line_width=4)
hover1=HoverTool(tooltips=[("x","@x"),("y","@y")])
fig1.add_tools(hover1)
x2=y2=list(range(10))
fig2=figs(width=400,height=400,title="plot2")
fig2.circle(x2,y2,size=5)
hover2=HoverTool(tooltips=[("x","@x"),("y","@y")])
fig2.add_tools(hover2)
show(row(fig1,fig2))

6.3D
import plotly.graph_objects as go
from plotly.offline import plot
students_data={
'Name':['Anil','Sunil','Kumar','Rajesh'],
'Height':[160,155,170,165],
'Weight':[55,50,65,60],
'Age':[20,19,21,20]
}
hover_text=[('Name:{name}<br> Height:{height}<br>Weight:{weight}<br>Age:{agre}'
for name,height,weight,age in zip(students_data['Name'],
students_data['Height'],students_data['Weight'],students_data['Age'] ))]
fig=go.Figure(data=[go.Scatter3d(
x=students_data['Height'],
y=students_data['Weight'],
z=students_data['Age'],
mode='markers',
marker=dict(size=10,color="blue",opacity=0.8),text=hover_text)])
fig.update_layout(scene=dict(xaxis_title='Height',yaxis_title='Weight',
zaxis_title='Age'),title='3D scatter plot of students Data')
plot(fig,filename='student_plot.html')

7A.TIME SERIES
import plotly.express as px
import pandas as pd
from plotly.offline import plot

# Corrected data dictionary


data = {
'Date': pd.date_range(start='2024-01-01', periods=5, freq='D'), # Correct date range
and frequency
'Studing_hr': [4, 3, 2, 5, 1], # Corrected typo in 'Studing_hr'
'Sleep_hr': [7, 6, 7, 8, 7]
}

# Create DataFrame
df = pd.DataFrame(data)

# Create line plot


fig = px.line(
df,
x='Date',
y=['Studing_hr', 'Sleep_hr'], # Correct way to specify multiple columns
color_discrete_sequence=['blue', 'green'],
title="Engineering students Studying & Sleeping Time Series", # Fixed typo in title
labels={'value': 'Hours', 'variable': 'Activity'} # Corrected label mappings
)

# Update layout for legend title


fig.update_layout(legend_title_text='Activity')

# Save the plot to an HTML file


plot(fig, filename='student_statistics.html')
7B.MAP
import plotly.express as px
from plotly.offline import plot
gapminder_data=px.data.gapminder()
df=gapminder_data.query("year==2007")
fig=px.scatter_geo(df,locations="iso_alpha",color="continent",hover_name="country",
size="pop",projection="natural earth")
plot(fig,filename='map.html')

You might also like