Python - Matplotlib

 

Matplotlib

Matplotlib içindəki pyplot vasitəsilə məlumatları qrafiklərə çevirəbilir və daha oxunabilən hala gətirir.

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt

from matplotlib import pyplot as plt

a = np.arange(1,11)
b = np.random.randint(1,50,10)

a

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

b

array([26, 22, 32, 26, 30, 49, 21, 37, 17, 48])

Qrafik hazırlamaq

plt.plot(a,b, color = 'red')
plt.xlabel('A deyerleri')
plt.ylabel('B deyerleri')
plt.title('A-B qrafiki')
plt.show()

Qrafiki alt parçalara bölmək (Subplot)

plt.subplot(setir_sayi, sutun_sayi, index)

plt.figure(figsize = (10,10))

plt.subplot(2, 1, 1)
plt.plot(a,b, 'green')
plt.title('Birinci qrafik')

plt.subplot(2,1,2)
plt.plot(a,b, 'red')
plt.title('Ikinci qrafik')

plt.show()

plt.figure(figsize = (15,6))
plt.subplot(2,2,1)
plt.plot(a,b, 'blue')
plt.title('Birinci qrafik')

plt.subplot(2,2,2)
plt.plot(a,b, 'red')
plt.title('Ikinci qrafik')

plt.subplot(2,2,3)
plt.plot(a,b, 'green')
plt.title('Ucuncu qrafik')

plt.tight_layout()
plt.show()

#Birinci hansini hazirlamaq istediyimizi yaziriq, sonra da qrafiki cekirik

#Burda birinci qrafiki yaziriq
plt.subplot(1,2,1)
plt.plot(x,y,"red")

#Burda ise ikinci qrafiki yaziriq
plt.subplot(1,2,2)
plt.plot(x,y,"blue")

#Bir setrde olmagina ehtiyac yoxdur. 2 setr, 2 sutun da ede bilerik

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

#1-ci index
plt.subplot(2,2,1)
plt.plot(a,b,"red")
plt.title("1-ci qrafik")

#2-ci index
plt.subplot(2,2,2)
plt.plot(a,b,"blue")
plt.title("2-ci qrafik")

#3-cu index
plt.subplot(2,2,3)
plt.plot(a,b,"black")
plt.title("3-cu qrafik")

#4-cu index
plt.subplot(2,2,4)
plt.plot(a,b,"pink")
plt.title("4-cu qrafik")

plt.show()

Figure və Axes yaratma

add_axes([sol, asagi, eni, hundurluyu])

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

axes = fig.add_axes([0,0,2,1])
axes.plot(a,b, 'red')
axes.set_xlabel('A deyerleri')
axes.set_ylabel('B deyerleri')
axes.set_title('Birinci')

axes2 = fig.add_axes([2,1,1,2])
axes2.plot(a,b, 'blue')
axes2.set_xlabel('A deyerleri')
axes2.set_ylabel('B deyerleri')
axes2.set_title('Ikinci')

axes3 = fig.add_axes([0,1.2,1.9,2])
axes3.plot(a,b, 'green')
axes3.set_xlabel('A deyerleri')
axes3.set_ylabel('B deyerleri')
axes3.set_title('Ucuncu')

plt.tight_layout()
plt.show()

<ipython-input-31-b87f1f84b8b2>:21: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.
  plt.tight_layout()

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

axes = fig.add_axes([0,0,1,1])
axes.plot(x,y, 'darkgray')
axes.set_xlabel('X deyerleri')
axes.set_ylabel('Y deyerleri')
axes.set_title('X-Y Qrafiki')

plt.show()

#Birinci ozumuze bir fiqur yaratmaliyiq

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

#Sonra ise axisler elave edirik bura. Ilk ikisi baslangic noqteleri, digerleri ise eni ve uzunlugu olacaq

axes = fig.add_axes([0,0,1,1])
axes.plot(x,y,"red")
axes.set_xlabel("X deyerleri")
axes.set_ylabel("Y deyerleri")
axes.set_title("X vs Y Qrafiki")
plt.show()


Axes stil vermək

  1. linsetyle: Xəttin stilini müəyyən edir.

  2. linewidth: Xəttin qalınlığını müəyyən edir.

  3. marker: dəyərlərin birləşdiyi yerin formasını müəyyən edir.

  4. markeredgecolor: Dəyərlərin birləşdiyi yerin rəngini müəyyən edir.

  5. markeredgewidth: Dəyərlərin birləşdiyi yerin qalınlığını müəyyən edir.

a

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

plt.plot(a,a)
plt.plot(a,a**2)
plt.plot(a, a**3)

[<matplotlib.lines.Line2D at 0x1c64e11ae50>]

x = a

x

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])


#xetlerin qalinligi ucun linewidth istifade edirik

fig,axes = plt.subplots(figsize = (10,8))

axes.plot(x,x, label = "X", color = "red", linewidth = 2)
axes.plot(x,x**2, label = "X^2", color = "blue", linewidth = 3)
axes.plot(x,x**3, label = "X^3", color = "yellow", linewidth = 4)
axes.plot(x,x**4, label = "X^4", color = "orange", linewidth = 5)


axes.legend()
plt.show()

#Stil vermek ucun linestyle istifade edirik

fig,axes = plt.subplots(figsize = (10,8))

axes.plot(x,x, label = "X", color = "red", linewidth = 2, linestyle = "-")
axes.plot(x,x**2, label = "X^2", color = "blue", linewidth = 3, linestyle = "--")
axes.plot(x,x**3, label = "X^3", color = "green", linewidth = 4, linestyle = "-.")
axes.plot(x,x**4, label = "X^4", color = "orange", linewidth = 5, linestyle = ":")


axes.legend()
plt.show()

#x-y deyerlerinin kesisdiyi yerler(markerlar) ucun istifade olunucaq.

fig,axes = plt.subplots(figsize = (15,7))

axes.plot(x,x, label = "X", color = "red", linewidth = 2, linestyle = "-", marker = "*")
axes.plot(x,x**2, label = "X^2", color = "blue", linewidth = 3, linestyle = "--", marker = "v")
axes.plot(x,x**3, label = "X^3", color = "yellow", linewidth = 4, linestyle = "-.", marker = ".")
axes.plot(x,x**4, label = "X^4", color = "orange", linewidth = 5, linestyle = ":", marker = "^")


axes.legend()
plt.show()

#Markeredgecolor vasitesile markerlarin rengini deyisdire bilersiniz.

fig,axes = plt.subplots(figsize = (15,7))

axes.plot(x,x, label = "X", color = "red", linewidth = 2, linestyle = "-", marker = "o", markeredgecolor = "black")
axes.plot(x,x**2, label = "X^2", color = "blue", linewidth = 3, linestyle = "--", marker = "v", markeredgecolor = "black")
axes.plot(x,x**3, label = "X^3", color = "yellow", linewidth = 4, linestyle = "-.", marker = ".", markeredgecolor = "black")
axes.plot(x,x**4, label = "X^4", color = "orange", linewidth = 5, linestyle = ":", marker = "^", markeredgecolor = "black")

axes.legend()
plt.show()

#Eger gorunmurse, hecmini de artira bilirik

fig,axes = plt.subplots(figsize = (15,7))

axes.plot(x,x, label = "X", color = "red", linewidth = 2, linestyle = "-", marker = "o", markeredgecolor = "black", markeredgewidth = 3)
axes.plot(x,x**2, label = "X^2", color = "blue", linewidth = 3, linestyle = "--", marker = "v", markeredgecolor = "black",markeredgewidth = 3)
axes.plot(x,x**3, label = "X^3", color = "yellow", linewidth = 4, linestyle = "-.", marker = ".", markeredgecolor = "black", markeredgewidth = 3)
axes.plot(x,x**4, label = "X^4", color = "orange", linewidth = 5, linestyle = ":", marker = "^", markeredgecolor = "black", markeredgewidth = 3)


axes.legend()

<matplotlib.legend.Legend at 0x1c64df90c40>

Pie Chart

df = pd.read_csv(r"C:\Users\Tunjay Majnunlu\Desktop\New Group\Dərs 7\Bank Data.csv")

df.head()

       ID Customer_ID     Month             Name  Age          SSN Occupation  \
0  0x1602   CUS_0xd40   January    Aaron Maashoh   23  821-00-0265  Scientist  
1  0x160f  CUS_0x21b1  February  Rick Rothackerj   28  004-07-5839    Teacher  
2  0x1612  CUS_0x21b1       May  Rick Rothackerj   28  004-07-5839    Teacher  
3  0x1613  CUS_0x21b1      June  Rick Rothackerj   28  004-07-5839    Teacher  
4  0x1615  CUS_0x21b1    August  Rick Rothackerj   28  004-07-5839    Teacher  

  Annual_Income  Num_Bank_Accounts  Num_Credit_Card  Interest_Rate  \
0       19114.12                  3                4              3  
1       34847.84                  2                4              6  
2       34847.84                  2                4              6  
3       34847.84                  2                4              6  
4       34847.84                  2                4              6  

  Delay_from_due_date  Num_of_Delayed_Payment  Outstanding_Debt  \
0                    3                       7            809.98  
1                    7                       1            605.03  
2                    3                       1            605.03  
3                    3                       0            605.03  
4                    3                       4            605.03  

      Credit_History_Age                Payment_Behaviour Monthly_Balance  \
0   22 Years and 1 Months  High_spent_Small_value_payments     312.4940887  
1   26 Years and 8 Months  High_spent_Large_value_payments     484.5912143  
2  26 Years and 11 Months   Low_spent_Small_value_payments     444.8670319  
3   27 Years and 0 Months  High_spent_Large_value_payments     481.5052619  
4   27 Years and 2 Months   Low_spent_Small_value_payments     356.0781086  

  Credit_Score 
0         Good 
1         Good 
2         Good 
3         Good 
4         Good  

df.groupby('Credit_Score')['Annual_Income'].mean()

Credit_Score
Good        64391.282344
Poor        39812.290094
Standard    50838.391554
Name: Annual_Income, dtype: float64

plt.figure(figsize = (7,7))
plt.pie(df.groupby('Credit_Score')['Annual_Income'].mean(), labels = df.groupby('Credit_Score')['Annual_Income'].mean().index, autopct = '%1.0f%%', explode = [0.1, 0.3, 0.1])

plt.show()

Bar Chart

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

plt.bar(df.groupby('Credit_Score')['Annual_Income'].mean().index, df.groupby('Credit_Score')['Annual_Income'].mean())
for i in range(len(df.groupby('Credit_Score')['Annual_Income'].mean())):
    plt.annotate(str(df.groupby('Credit_Score')['Annual_Income'].mean()[i]), xy = (df.groupby('Credit_Score')['Annual_Income'].mean().index[i],df.groupby('Credit_Score')['Annual_Income'].mean()[i]), ha = "center", va = "bottom")

plt.show()

Scatter Plot

import seaborn as sns

df = sns.load_dataset('iris')

df.head()

   sepal_length  sepal_width  petal_length  petal_width species
0           5.1          3.5           1.4          0.2  setosa
1           4.9          3.0           1.4          0.2  setosa
2           4.7          3.2           1.3          0.2  setosa
3           4.6          3.1           1.5          0.2  setosa
4           5.0          3.6           1.4          0.2  setosa

plt.scatter(df['sepal_length'], df['petal_length'])

<matplotlib.collections.PathCollection at 0x1c6523f7430>

df

     sepal_length  sepal_width  petal_length  petal_width    species
0             5.1          3.5           1.4          0.2     setosa
1             4.9          3.0           1.4          0.2     setosa
2             4.7          3.2           1.3          0.2     setosa
3             4.6          3.1           1.5          0.2     setosa
4             5.0          3.6           1.4          0.2     setosa
..            ...          ...           ...          ...        ...
145           6.7          3.0           5.2          2.3  virginica
146           6.3          2.5           5.0          1.9  virginica
147           6.5          3.0           5.2          2.0  virginica
148           6.2          3.4           5.4          2.3  virginica
149           5.9          3.0           5.1          1.8  virginica

[150 rows x 5 columns]

sns.lmplot(x = 'sepal_length', y = 'petal_length', data = df)

<seaborn.axisgrid.FacetGrid at 0x1c65242c940>

df['petal_length'].corr(df['sepal_length'])

0.871753775886583

plt.scatter(df['Annual_Income'], df['Age'])

<matplotlib.collections.PathCollection at 0x1c6504d48b0>


Histogram Plot

df['sepal_length'].max()
df['sepal_length'].min()

4.3

7.9 - 4.3

3.6000000000000005

plt.hist(df['sepal_length'])

(array([ 9., 23., 14., 27., 16., 26., 18.,  6.,  5.,  6.]),
array([4.3 , 4.66, 5.02, 5.38, 5.74, 6.1 , 6.46, 6.82, 7.18, 7.54, 7.9 ]),
<BarContainer object of 10 artists>)

#Men istesem ordaki sinifleri deyisdire bilerem
plt.figure(figsize = (12,6))
bins = np.linspace(df['sepal_length'].min(), df['sepal_length'].max(), 15)
plt.xticks(bins)
plt.hist(df['sepal_length'], n_bins)

(array([ 4.,  5.,  7., 16.,  9.,  5., 13., 14., 10.,  6., 10., 16.,  7.,
        11.,  4.,  2.,  4.,  1.,  5.,  1.]),
array([4.3 , 4.48, 4.66, 4.84, 5.02, 5.2 , 5.38, 5.56, 5.74, 5.92, 6.1 ,
        6.28, 6.46, 6.64, 6.82, 7.  , 7.18, 7.36, 7.54, 7.72, 7.9 ]),
<BarContainer object of 20 artists>)

#Biz birbasa bin sayini vere bilerik

x = np.random.randint(0,100,size = (20,1))
n_bins = 7
plt.hist(x,n_bins)

Area Plot


df.plot(kind = 'area', stacked = False)
plt.show()

#Burda sinifdeki telebelere gore qiymetleri vizuallasdiracagiq

qiymetler = {
    "Telebe1":[65,85,75,95],
    "Telebe2":[45,55,80,90]
}

dersler = ["Az_dili", "Riyaziyyat", "Fizika", "Kimya"]

df = pd.DataFrame(qiymetler, index = dersler)

df

            Telebe1  Telebe2
Az_dili          65       45
Riyaziyyat       85       55
Fizika           75       80
Kimya            95       90

df.plot(kind = 'area')

<AxesSubplot:>

df.plot(kind = "area", stacked = False)
plt.show()

#Amma burda bir qeribelik var. Ust uste cixib qrafikler

df.plot(kind = "area", stacked = False)
plt.show()

Line Plot

#Line plot eyni qaydada yazilir

qiymetler = {
    "Telebe1":[65,85,75,95],
    "Telebe2":[45,55,80,90]
}

dersler = ["Az_dili", "Riyaziyyat", "Fizika", "Kimya"]

df = pd.DataFrame(qiymetler, index = dersler)

df.plot(kind = "line", stacked = False)
plt.show()

Density Plot


df.plot(kind = "density", stacked = False)
plt.show()


Popular posts from this blog

Power BI DAX Functions

Python - Pandas

Power BI - Lifehacks