0% found this document useful (0 votes)
47 views

1a. Best of Two

The document contains 10 code snippets demonstrating various plotting techniques using libraries like matplotlib, seaborn, bokeh and plotly. It includes examples of bar plots, scatter plots, histograms, pie charts, linear plots and more. The last two snippets show examples using plotly express for line charts and choropleth maps.

Uploaded by

rasadhana05
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)
47 views

1a. Best of Two

The document contains 10 code snippets demonstrating various plotting techniques using libraries like matplotlib, seaborn, bokeh and plotly. It includes examples of bar plots, scatter plots, histograms, pie charts, linear plots and more. The last two snippets show examples using plotly express for line charts and choropleth maps.

Uploaded by

rasadhana05
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/ 7

1a.

Best of two
m1 = int(input("Enter marks 1: "))
m2 = int(input("Enter marks 2: "))
m3 = int(input("Enter marks 3: "))
print("The average of best if two is ", sum(sorted([m1,m2,m3],reverse=True)[:2])/2)

1b. Word count


num = input("Enter a number: ")
(num == num[::-1]) if print("Palindrome") else print("Not a Palindrome")
for i in range(10):
if num.count(str(i))>0:
print(f'{str(i)} appears {num.count(str(i))} times')

2a. Recursion
def Fn(n):
if n<= 2:
return n-1
else:
return Fn(n-1) + Fn(n-2)
try:
N = int(input("Enter a number: "))
if N > 0:
print(f'Fn({N}) = {Fn(N)}')
else:
print("Try with a no greater than 0")
except ValueError:
print("Try with a no")
2b. Bin to Dec, Oct to Hex
def bin_to_dec(bin):
dec=0
for digit in bin:
dec = dec*2 + int(digit)
return dec
def oct_to_hex(oct):
dec=0
for i,digit in enumerate(oct[::-1]):
dec += int(digit)*(8**i)
hex_chars = '0123456789ABCDEF'
hex_str = ''
while dec != 0:
hex_str += hex_chars[dec%16]
dec=dec//16
return hex_str
try:
bin_num = input("Enter a binary no.: ")
print(bin_to_dec(bin_num))
except ValueError:
print("Base 2")
try:
oct_num = input("Enter a octal no.: ")
print(oct_to_hex(oct_num))
except ValueError:
print("Base 8")
3a. No. of words, nos…..
sentence = input("Enter a sentence: ")
word_count = len(sentence.split())
print(f"This sentence has {word_count} words",
"\nDigits:", sum(1 for char in sentence if char.isdigit()),
"\nUppercase letters:",sum(1 for char in sentence if char.isupper()),
"\nLowercase letters:",sum(1 for char in sentence if char.islower()))

3b. String match


from difflib import SequenceMatcher
s1 = input("Enter string 1: ")
s2 = input("Enter string 2: ")
print("Similarity b/w "+ s1 + " and " + s2 + " is: ", SequenceMatcher(None,s1,s2).ratio())

4a. Bar
import matplotlib.pyplot as plt
countries = ['USA', 'India', 'Brazil', 'Russia', 'France']
cases = [31887644, 39034355, 23097697, 8620807, 20710628]
plt.bar(countries,cases)
plt.xlabel('Countries')
plt.ylabel('Cases')
plt.title('Bar Plot Example')
plt.show()

4b. Scatter
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
x = np.random.rand(10)
y = np.random.rand(10)
colors = np.random.rand(10)
sizes = 1000 * np.random.rand(10)
plt.scatter(x, y, c=colors, s=sizes, cmap='viridis', alpha=0.7)
plt.colorbar()
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot with Viridis Colormap')
plt.show()

5a. Histogram
import matplotlib.pyplot as plt
import numpy as npdata = np.random.randn(100)
plt.hist(data,bins=20,color='blue',edgecolor='black',alpha=0.7)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Histogram plot")
plt.show()

5b. Pie
import matplotlib.pyplot as plt
categories = ['Home decor','Electronics','Books','Clothes']
sales = [123456,234561,345612,456123]
plt.pie(sales,labels=categories,colors=['skyblue','lightgreen','lightcoral','lightsalmon'],autopct
='%1.1f',explode=[0.1,0.1,0.1,0.1])
plt.title("Pie Chart")
plt.show()
6a. Linear plot
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,20)
y = np.sin(x)+0.2*x**2
plt.plot(x,y,color='skyblue')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Linear Plot")
plt.show()

6b. Line Formatting


import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,20)
y = np.sin(x)+0.2*x**2
plt.plot(x,y,color='skyblue',marker='X',markerfacecolor='blue',markersize=8,linestyle='-',line
width=2)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Linear Plot")
plt.show()

7. Aesthetic functions
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
iris = pd.read_csv(r"C:\Users\Sadhana\PycharmProjects\DVP\pythonProject\iris.csv")
sns.scatterplot(x=iris['sepal_length'],y=iris['sepal_width'],data=iris,hue='species',palette='Set
2',alpha=0.7)
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.title('Iris')
plt.show()

8. Bokeh
from bokeh.plotting import figure,show
import numpy as np
x = np.linspace(0,4*np.pi,100)
y1 = np.sin(x)
y2 = np.cos(x)
plot = figure(title='Bokeh',x_axis_label='x',y_axis_label='y')
plot.scatter(x,y1,legend_label='sin(x)',fill_color='white',size=8)
plot.scatter(x,y2,legend_label='sin(x)',fill_color='red',size=8)
show(plot)

9. Plotly
import plotly.graph_objects as go
import pandas as pd
iris = pd.read_csv(r"C:\Users\Sadhana\PycharmProjects\DVP\pythonProject\iris.csv")
fig = go.Figure(data=[go.Scatter3d(x=iris['sepal_length'], y=iris['sepal_width'],
z=iris['petal_length'], mode='markers',
marker=dict(size=5,color='deeppink'))],layout=dict(title='3D Scatter Plot',
scene=dict(xaxis_title='Sepal length', yaxis_title='Sepal width', zaxis_title='Petal length')))
fig.show()
10a. Plotly express
import plotly.express as px
import pandas as pd
data = pd.read_csv(r"C:\Users\Sadhana\Downloads\CUR_DLR_INR .csv")
fig= px.line(data,x='DATE',y='RATE',title='DLR to INR')
fig.show()

10b. Plotly express


import plotly.express as px
import pandas as pd
data = pd.read_csv(r"C:\Users\Sadhana\PycharmProjects\DVP\pythonProject\
gapminder_with_codes.csv")
fig = px.choropleth(data_frame=data,locations='iso_alpha',projection='natural
earth',hover_name='country',color='gdpPercap',title='gdpPercap',)
fig.show()

You might also like