Thursday, 24 March 2022

P#16 Line, Bar, Scatter, Pie charts

MATPLOTLIB...

In this blog, we will see how to plot various chart types using plt.line(), plt.bar(), plt.barh(). plt.scatter(), plt.hist(). 
If you run this code which is self explanatory, you will get this chart. 
def plotline():
import matplotlib.pyplot as plt
langs = ['B.E CSE', 'B.E. Marine', 'B.E. ECE', 'B.Sc(NatSci)', 'MBA']
students = [20, 40, 60, 80, 100]
plt.plot(langs, students) # plot
plt.xlabel('Degree')
plt.ylabel('Strength')
plt.grid()
plt.savefig('line.png')
plt.show()
plotline()
If you run this code, you will get this chart. 
def plotbar():
langs = ['B.E CSE', 'B.E. Marine', 'B.E. ECE', 'B.Sc(NatSci)', 'MBA']
students = [20, 40, 60, 80, 100]
plt.bar(langs, students, col) # BAR
plt.xlabel('Degree')
plt.ylabel('Strength')
plt.grid()
plt.savefig('bar.png')
plt.show()
plotbar()

def plotbarh():
langs = ['B.E CSE', 'B.E. Marine', 'B.E. ECE', 'B.Sc(NatSci)', 'MBA']
students = [20, 40, 60, 80, 100]
plt.barh(langs, students, color = 'hotpink') # BARh Pink
plt.xlabel('Degree')
plt.ylabel('Strength')
plt.grid()
plt.savefig('bar.png')
plt.show()
plotbarh() plots horizontal bar as shown below.
def plotbarss():
import numpy as np
import matplotlib.pyplot as plt
data = [[30, 25, 50, 20],
[40, 23, 51, 17],
[35, 22, 45, 19]]
X = np.arange(4)
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.bar(X + 0.00, data[0], color='b', width=0.25)
ax.bar(X + 0.25, data[1], color='g', width=0.25)
ax.bar(X + 0.50, data[2], color='r', width=0.25)
ax.legend(labels=('cse', 'it', 'mech', 'mba'), loc='upper right')
plt.savefig('bars.png')
plt.show()
plotbarss() displays the chart as shown below with three bars.
def plotscat():
langs = ['B.E CSE', 'B.E. Marine', 'B.E. ECE', 'B.Sc(NatSci)', 'MBA']
students = [20, 40, 60, 80, 100]
plt.scatter(langs, students) # Scatter
plt.xlabel('Degree')
plt.ylabel('Strength')
plt.grid()
plt.savefig('scat.png')
plt.show()
plotscat()
plt.scatter() wil plot scatter plot as shown below()
def plotscatc():
np.random.seed(19680801) # seed the random number generator.
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.scatter('a', 'b', c='c', s='d', data=data, marker='*')
ax.set_xlabel('entry a')
ax.set_ylabel('entry b');
plt.savefig('scatcc.png')
plt.show()
plotscatc()
This will print different size, different colors.

This will print marker different size, different colors. 
marker = “*” sets the plot symbol as *. s = different size of the marker symbol in the plot. 

def plothist():
import matplotlib.pyplot as plt
import numpy as np
x = np.random.normal(170, 10, 250)
plt.hist(x)
plt.savefig('hist.png')
plt.show()
plt.hist() method plots histogram as shown below;
def plotpie():
import matplotlib.pyplot as plt
import numpy as np
y = np.array([32, 40, 60, 80, 100])
plt.pie(y)
plt.savefig('pie.png')
plt.show()
plotpie()
plot.pie() method to plot y.
def plotpie1():
deg = ['B.E CSE', 'B.E. Marine', 'B.E. ECE', 'B.Sc(NatSci)', 'MBA']
students = [20, 40, 60, 80, 100]
# Creating plot
fig = plt.figure(figsize=(8, 6))
plt.pie(students, labels=deg)
# show plot
plt.savefig('pie1.png')
plt.show()
plotpie1()

This is pie plot with labels. That is provide by plt.pie(students, labels=deg)

Happy learning with AMET ODL!!!




Wednesday, 23 March 2022

Plotting #15

MATPLOTLIB

Matplotlib is a low level graph plotting library in python that serves as a visualization utility.

Matplotlib was created by John D. Hunter.

Matplotlib is open source and we can use it freely.

Matplotlib is mostly written in python, a few segments are written in C, Objective-C and Javascript for Platform compatibility.

Matplotlib என்பது பைத்தானில் உள்ள ஒரு குறைந்த அளவிலான வரைபடத் திட்டமிடல் நூலகமாகும், இது காட்சிப்படுத்தல் பயன்பாடாக செயல்படுகிறது.

Matplotlib ஜான் டி. ஹண்டர் என்பவரால் உருவாக்கப்பட்டது.

Matplotlib திறந்த மூலமாகும், அதை நாம் சுதந்திரமாகப் பயன்படுத்தலாம்.

Matplotlib பெரும்பாலும் python இல் எழுதப்பட்டுள்ளது, ஒரு சில பிரிவுகள் C, Objective-C மற்றும் Javascript இல் பிளாட்ஃபார்ம் இணக்கத்தன்மைக்காக எழுதப்பட்டுள்ளன.


import matplotlib.pyplot as plt
import numpy as np

x = [1, 2, 3, 4, 5 ]
ls = [2, 4, 6, 8, 10]
d = [0, 1, 1, 2, 2 ]

def plot1():
plt.plot(x,ls)
plt.title('1. First Graph') ###
plt.savefig('v31.png')
plt.show()
plot1()
Simple definition for x, ls as list. Normally matplotlib is extensively used with np. 
Here we take minimum lists x, ls for plotting for easy understanding. 
Very simple import matplotlib, plot() with two declared lists, and show.
If u want you can save using savefig() method. This is written as function using def. 
You can simply call by plot1()
def plot2():
plt.plot(x,ls,'r-')
plt.title('2. Graph with Axes Labels and red')
plt.xlabel('X-Axis') ##
plt.ylabel('Y-Axis') ##
plt.savefig('v32.png')
plt.show()
plot2()
 The above plot2() will add title title and axis using plt.title() and plt.xlabel() and 
plt.ylabel() methods as shown above. see the result as below.


def plot3():
plt.plot(x,ls,'g-')
plt.title('3. Graph with Axes Labels + Grid Lines + Green')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.grid() #####
plt.savefig('v33.png')
plt.show()
plot3()
The above code uses plt.axis() method to add axis in the graph. The output will be similar to 
the one shown below:

def plot4():
fig = plt.figure(figsize=(5, 4))
plt.plot(x,ls,'r-')
plt.title('4. Check the Figure Size ')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.grid()
plt.savefig('v34.png')
plt.show()
plot4()
figure size is defined by fig = plt.figure(figsize=(5, 4)). Check he effect of this statement 
as shown below. 

def plot5():
fig = plt.figure(figsize=(5, 4))
plt.plot(x, x,'b-', x, ls,'r-', x, d, 'g-')
plt.title('5. Multiple Plots ')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.grid()
plt.savefig('v35.png')
plt.show()
plot5()
See the multiple data can be plotted in a single graphs by the plt.plot(x, x,'b-', x, ls,'r-', x, d, 'g-')
Please notice the 'b-' to denote blue normal line, 'g-' to denote the green line. See the result:
def plot6():
# using numparray
fig = plt.figure(figsize=(5, 4))
x = np.array([1, 2, 3, 4, 5])
ls = np.array([2, 4, 6, 8, 10])
d = np.array([0, 1, 1, 2, 2])
plt.plot(x, x,'b-')
plt.plot(x, ls,'r-')
plt.plot(x, d, 'g-')
plt.title('6. Multiple Plots using np array')
plt.xlabel('Quantity')
plt.ylabel('Price')
plt.grid()
plt.savefig('v36.png')
plt.show()
plot6()
This code snippet is another way, used separate plt.plot() statements. Also data set is defined as num arrays.
See the result graph as shown below.


def plot7():
x = np.array([1, 2, 3, 4, 5])
ls = np.array([2, 4, 6, 8, 10])
d = np.array([0, 1, 1, 2, 2])

plt.title('6. MultipleSub Plots Column wise')
# plot 1:
plt.subplot(1, 2, 1)
plt.plot(x, x)
plt.title('Qty Vs Qty')

# plot 2:
plt.subplot(1, 2, 2)
plt.plot(x, ls)
plt.title('Qty Vs Price')
plt.savefig('v37.png')
plt.show()
plot7()
This plot explains the sub plots. plt.subplot(1, 2, 1) indicates the graph has 1 row, 2 columns, and this 
plot is the first plot. plt.supplot(1, 2, 2) indicates figure has 1 row, 2 columns, and this plot is the
second plot. See the graph below to depict the above code snippet.


def plot8():
x = np.array([1, 2, 3, 4, 5])
ls = np.array([2, 4, 6, 8, 10])
d = np.array([0, 1, 1, 2, 2])
plt.title('6. Sub Plots Row wise using np array')

# plot 1:
plt.subplot(2, 2, 1)
plt.plot(x, x)
plt.title('Qty Vs Qty')
    # plot 2:
plt.subplot(2, 2, 2)
plt.plot(x, ls)
plt.title('Quantity Vs Price')
plt.savefig('v38.png')
plt.show()
plot8()
The output graph is given above side by side  to compare between the snippets
plt.subplot(1, 2, 1),  plt.supplot(1, 2, 2) Vs plt.subplot(2, 2, 1) and plt.subplot(2, 2, 2)
Happy learning with AMET ODL🙋🙋🙋!!!

Tuesday, 22 March 2022

Python Visualizing λ

λ +

Python compact coding is very much possible with lambda function.

Anonymous function.. Function without name. 

# lambda arguments : expression

# using Lambda
result = lambda x,y : x + y
# print(result(5,5))

# otherwise by function
def add(x,y):
return (x+y)
add(5,5)

sorted() takes elements from the list and sort the elements. Please see how key is implemented using lambda function. This can be used for any list with numbers, strings, list of lists. For simple understanding, number list is given. keys are defined using lambda arguments.


# Difference Between function and lambda -anonymous function
def cube(x):
return (x*x*x)

lambda_cube = lambda x: x*x*x

print(cube(125))
print((lambda_cube(25))) # No function call or return

list_of_tuples = [(1, 2, 3, 4), (4, -3, 2, 1), (3, 4, -1, 2), (2, 3, 4, -1)]
list_of_tuples_sorted = sorted(list_of_tuples)
print(list_of_tuples_sorted)
"""
[(1, 2, 3, 4), (2, 3, 4, -1), (3, 4, -1, 2), (4, -3, 2, 1)]
"""

list_of_tuples_sorted = sorted(list_of_tuples, key =lambda x: x[1]) # Sort in second element of all tuples
print(list_of_tuples_sorted)
"""
[(4, -3, 2, 1), (1, 2, 3, 4), (2, 3, 4, -1), (3, 4, -1, 2)]
"""

list_of_tuples_sorted = sorted(list_of_tuples, key =lambda x: x[3]) # Sort in last element of all tuples
print(list_of_tuples_sorted)

"""
[(2, 3, 4, -1), (4, -3, 2, 1), (3, 4, -1, 2), (1, 2, 3, 4)] """
Map function is used to pass the arguments from the list. Literally mapping values..
# Using function map()
alist = [1, 2, 3, 4, 5]
mlist =
map(lambda x : x*x, alist) # map supplies elements instead of one element
print(list(mlist)) # [1, 4, 9, 16, 25]

# Otherwise using c-omprehensive list
clist = [x * x for x in alist]
print(clist) # [1, 4, 9, 16, 25]
#Using Filter to find even numbers in the list
flist = filter(lambda x: x%2 == 0, alist)
print(list(flist)) # [2, 4]

# Otherwise using c-omprehensive list
clist = [x for x in alist if x%2== 0]
print(clist) # [2, 4]
#Using reduce ....please import reduce from functools

def my_add(a, b):
   result = a + b
print(f"{a} + {b} = {result}")
return result

from functools import reduce
numbers = [0, 1, 2, 3, 4]
print(reduce(my_add, numbers))

# Note passing a,b and see the cumulative sum is first
element in the next iteration

0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10
"""
import functools

# list definition
alist = [1, 2, 7, 4, 5, 6, 3, ]

# educe to compute sum of list
print("The sum of the list elements is : ", end="")
print(functools.reduce(lambda a, b: a + b, alist)) #28

# reduce to compute maximum element from list
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, alist)) # 7

To understand the visualization the above reduce code execution: please click the  link https://pythontutor.com/visualize.html#mode=display Paste the above code in the editor window. Click visualize execution and next button. 

Step 1:


Step 2: Delete the first line (if any) as shown in the above screen shot. 
Paste the copied code as shown below


Step 3: Click Visualize Button to see the screen shot similar to the following one:


Step 4: Click Next Button to see the following 



Please note global frame with functools points with arrow to  objects module instance by arrow.

Step 5: Click Next button again to see as shown below



Notice the pointer from alist  1,2,7,4,5.  

Step 5: Click again to see the window similar to one shown below:



Please note the print out box in top right : First print out put 
'The sum of the list elements is seen  :'

Step 6:  Again Click Next  to see the window as shown below.


In this screen shot, please notice  lambda list with a =1 ,b=2 . Press Clicks to see the screen below to see the return value 3:



Step 7:.. Click Next many times until that button is disabled  to see execution until you get results 
The maximum element of the list is : 7  as shown in the screen below.


This is the video showing the execution.


Hope, you understand the execution of the python code. 

Hey, you know how to write concise coding using Lambda.. If you don't, sorry, God only save you!!!!😇

Happy Learning with AMET, ODL


Pandas#02

 PANDAS .... (Analysing)

# Analyzing Data Frames
print(df.info())
"""
Int64Index: 169 entries, 0 to 168
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Duration 169 non-null int64
1 Pulse 169 non-null int64
2 Maxpulse 169 non-null int64
3 Calories 164 non-null float64
dtypes: float64(1), int64(3)
memory usage: 6.6 KB
None
"""

The info() method also tells 

  • Non-Null values there are present in each column, (164 of 169 Non-Null values in the "Calories" column.) . 
  • 5 rows with no value at all, in the "Calories" column, for whatever reason.
  • Empty values, or Null values, can be bad when analyzing data, duplicate values and 
  • Removing rows with empty values  called cleaning data, and you will learn more about that in the next chapters.
Let us dive in to the code for cleaning. Assume the data file as dirtydata.csv


import pandas as pd
df = pd.read_csv('dirtydata.csv') # reading dirty
# print(df)
"""
Duration Date Pulse Maxpulse Calories
0 60 '2020/12/01' 110 130 409.1
1 60 '2020/12/02' 117 145 479.0
2 60 '2020/12/03' 103 135 340.0
3 45 '2020/12/04' 109 175 282.4
4 45 '2020/12/05' 117 148 406.0
5 60 '2020/12/06' 102 127 300.0
6 60 '2020/12/07' 110 136 374.0
7 450 '2020/12/08' 104 134 253.3
8 30 '2020/12/09' 109 133 195.1
9 60 '2020/12/10' 98 124 269.0
10 60 '2020/12/11' 103 147 329.3
11 60 '2020/12/12' 100 120 250.7
12 60 '2020/12/12' 100 120 250.7
13 60 '2020/12/13' 106 128 345.3
14 60 '2020/12/14' 104 132 379.3
15 60 '2020/12/15' 98 123 275.0
16 60 '2020/12/16' 98 120 215.2
17 60 '2020/12/17' 100 120 300.0
18 45 '2020/12/18' 90 112 NaN
19 60 '2020/12/19' 103 123 323.0
20 45 '2020/12/20' 97 125 243.0
21 60 '2020/12/21' 108 131 364.2
22 45 NaN 100 119 282.0
23 60 '2020/12/23' 130 101 300.0
24 45 '2020/12/24' 105 132 246.0
25 60 '2020/12/25' 102 126 334.5
26 60 20201226 100 120 250.0
27 60 '2020/12/27' 92 118 241.0
28 60 '2020/12/28' 103 132 NaN
29 60 '2020/12/29' 100 132 280.0
30 60 '2020/12/30' 102 129 380.3
31 60 '2020/12/31' 92 115 243.0
"""
print(df.info)
"""
<bound method DataFrame.info of Duration Date Pulse Maxpulse Calories
0 60 '2020/12/01' 110 130 409.1
1 60 '2020/12/02' 117 145 479.0
2 60 '2020/12/03' 103 135 340.0
3 45 '2020/12/04' 109 175 282.4
4 45 '2020/12/05' 117 148 406.0
5 60 '2020/12/06' 102 127 300.0
6 60 '2020/12/07' 110 136 374.0
7 450 '2020/12/08' 104 134 253.3
8 30 '2020/12/09' 109 133 195.1
9 60 '2020/12/10' 98 124 269.0
10 60 '2020/12/11' 103 147 329.3
11 60 '2020/12/12' 100 120 250.7
12 60 '2020/12/12' 100 120 250.7
13 60 '2020/12/13' 106 128 345.3
14 60 '2020/12/14' 104 132 379.3
15 60 '2020/12/15' 98 123 275.0
16 60 '2020/12/16' 98 120 215.2
17 60 '2020/12/17' 100 120 300.0
19 60 '2020/12/19' 103 123 323.0
20 45 '2020/12/20' 97 125 243.0
21 60 '2020/12/21' 108 131 364.2
23 60 '2020/12/23' 130 101 300.0
24 45 '2020/12/24' 105 132 246.0
25 60 '2020/12/25' 102 126 334.5
26 60 20201226 100 120 250.0
27 60 '2020/12/27' 92 118 241.0
29 60 '2020/12/29' 100 132 280.0
30 60 '2020/12/30' 102 129 380.3
31 60 '2020/12/31' 92 115 243.0>
"""
df.dropna(inplace = True)
# print(df.to_string())
print(df) # check no values are dropped
"""
Duration Date Pulse Maxpulse Calories
0 60 '2020/12/01' 110 130 409.1
1 60 '2020/12/02' 117 145 479.0
2 60 '2020/12/03' 103 135 340.0
3 45 '2020/12/04' 109 175 282.4
4 45 '2020/12/05' 117 148 406.0
5 60 '2020/12/06' 102 127 300.0
6 60 '2020/12/07' 110 136 374.0
7 450 '2020/12/08' 104 134 253.3
8 30 '2020/12/09' 109 133 195.1
9 60 '2020/12/10' 98 124 269.0
10 60 '2020/12/11' 103 147 329.3
11 60 '2020/12/12' 100 120 250.7
12 60 '2020/12/12' 100 120 250.7
13 60 '2020/12/13' 106 128 345.3
14 60 '2020/12/14' 104 132 379.3
15 60 '2020/12/15' 98 123 275.0
16 60 '2020/12/16' 98 120 215.2
17 60 '2020/12/17' 100 120 300.0
19 60 '2020/12/19' 103 123 323.0
20 45 '2020/12/20' 97 125 243.0
21 60 '2020/12/21' 108 131 364.2
23 60 '2020/12/23' 130 101 300.0
24 45 '2020/12/24' 105 132 246.0
25 60 '2020/12/25' 102 126 334.5
26 60 20201226 100 120 250.0
27 60 '2020/12/27' 92 118 241.0
29 60 '2020/12/29' 100 132 280.0
30 60 '2020/12/30' 102 129 380.3
31 60 '2020/12/31' 92 115 243.0
"""
See the last result output doesn't have NaN values. inplace = True, it will clean in the same place.

dropna() will delete the rows with NaN.














































index.html

Mobile Tea/Coffee POS Chai POS Mobile Tea/Coffee & Snacks Billing ...