Python MatPlotLib Modülü

09.02.2025
83
Python MatPlotLib Modülü

Python MatPlotLib modülü Matematik ve İstatistik biliminin ortak kesişim kümesi olan Veri Analizinin grafiklerle görselleştirilmesi için geliştirilmiştir. MatPlotLib ile 2 boyutlu çizgi grafiklerinden tutun lineer grafiklere hatta çok boyutlu grafiklere kadar birçok türde grafiğe dönüştürebilirsiniz.

MatPlotLib Kütüphanesi ile ilgili döküman, örnekler ve çözümler için aşağıdaki bağlantıyı kullanabilirsiniz.

MatplotLib kütüphanesi ile birlikte NumPy ve Pandas kütüphanelerini de projenize import etmeyi ve Python çekirdeğine install etmeyi unutmayınız.

pip install matplotlib
pip install numpy
pip install pandas

Python MatPlotLib kullanarak ilk grafiğimizi oluşturmak için aşağıdaki kodları yazalım.

import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


age = [25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45]
height = [168, 134, 210, 174, 176, 188, 180, 150, 184, 121, 188]

np_age = np.array(age) # convert list to numpy array
np_height = np.array(height) # convert list to numpy array

plt.xlabel('Age') # x-axis label
plt.ylabel('Height') # y-axis label
plt.title('Age vs Height') # title of the graph
plt.plot(np_age, np_height,"g") # g is for green color
plt.show() # display the graph
Python

Grafik Çıktısı:

matplotlib modülü örnek

Kod bloğunda girişi yapılan veri setinin en basit grafiksel gösterimi Python MatPlotLib kütüphanesi ile gösterimi bu şekildedir.

MatPlotLib Modülü Grafik Türleri

Yazımızın başında vermiş olduğumuz linklerden MatPlotLib kütüphanesinin resmi sayfasında bulunan Examples bölümünü incelediğinizde bir çok grafik türü ve nasıl kullanıldığı hakkında dökümana ulaşabilirsiniz. MatPlotLib grafik türlerinden en çok kullanılanlara göz atacağız.

Eğri Grafiği

Sinüsel, parabolik ve eğri grafikleri de plot metodu ile çizdirebiliriz. Ancak bunun için üstel olarak artışa sahip bir veri seti gerekiyor. Biraz matematik tecrübemizi kullanıp NumPy kütüphanesi ile oluşturduğumuz lineer veri setinin karelerini alarak üstel artışa sahip yeni bir veri seti oluşturalım.

import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


new_numpay1 = np.linspace(0, 10, 20) # 20 numbers between 0 and 10
new_numpay2 = new_numpay1 ** 2 # square of each number in new_numpay1
print(new_numpay2) 

plt.plot(new_numpay1, new_numpay2, 'r') # r is for red color
plt.show() # display the graph
Python

Grafik Çıktısı:

Eğer plot metodu içinde veri setlerini birbiri ile yer değiştirirsek grafikte değişecektir.

  • plt.plot(new_numpay2, new_numpay1, ‘r’)
import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


new_numpay1 = np.linspace(0, 10, 20) # 20 numbers between 0 and 10
new_numpay2 = new_numpay1 ** 2 # square of each number in new_numpay1
print(new_numpay2) 

plt.plot(new_numpay2, new_numpay1, 'r') # r is for red color
plt.show() # display the graph
Python

Grafik Çıktısı:

matplot lineer pow chart

Grafik Stil Parametreleri

Grafik üzerinde renk ve opasite değerlerini değiştirmek için color= ve alpha= parametrelerini kullanabilirsiniz. Çizgi kalınlığını ve şeklini ise linewidth= ve linestyle= ile belirliyoruz. Aynı şekilde marker yani kesişim noktalarına işaretçi eklemek ve bunun özelliklerini değiştirmek için marker= ve markersize= parametrelerini ekliyoruz.

  • plt.plot(new_numpay2, new_numpay1, color=”#renk_hex_kod”, alpha=float_deger, linewidth=cizgi_kalinligi_float, linewidth=5, linestyle=”-.”)
import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


new_numpay1 = np.linspace(0, 10, 20) # 20 numbers between 0 and 10
new_numpay2 = new_numpay1 ** 1.3 # square of each number in new_numpay1
print(new_numpay2) 

ax2.plot(new_numpay3, new_numpay3 + 3, color="#00FF88", linewidth=4.5, linestyle=":", marker="+", markersize=10) 

plt.show() # display the graph
Python

Grafik Çıktısı:

MatPlotLib Kütüphanesini kullanarak oluşturduğumuz grafikte dikey olan eğrinin transparan olduğunu görebilirsiniz. alpha değerini 0 ile 1 arasında değiştirerek ayarlayabilirsiniz. Ayrıca gri renkteki transparan çizginin daha kalın olduğunu da görebilirsiniz.

Grafik Üzerinde Data Point Oluşturma

Grafik rengini belirlerken renk harfinin sonuna * – . + gibi sembollerden birini yazarsanız grafikte noktalar o sembolle temsil edilecektir.

  • plt.plot(new_numpay2, new_numpay1, ‘r+’)
import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


new_numpay1 = np.linspace(0, 10, 20) # 20 numbers between 0 and 10
new_numpay2 = new_numpay1 ** 2 # square of each number in new_numpay1
print(new_numpay2) 

plt.plot(new_numpay2, new_numpay1, 'r+') # r is for red color + is for plus sign
plt.show() # display the graph
Python

Grafik Çıktısı:

Hem Çizgi Hem Sembol ile Grafik Çizme

MatPlotLib Modülünde grafik çizerken kesişim noktaları ve çizgi üst üste olsun isterseniz sembolden sonra – yani tire işareti koymanız yeterli olacaktır.

  • plt.plot(new_numpay1, new_numpay2, ‘r.-‘)
import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


new_numpay1 = np.linspace(0, 10, 20) # 20 numbers between 0 and 10
new_numpay2 = new_numpay1 ** 2 # square of each number in new_numpay1
print(new_numpay2) 

plt.plot(new_numpay1, new_numpay2, 'r.-') # r is for red color + is for plus sign

plt.show() # display the graph
Python

Grafik Çıktısı:

Subplot() Metodu ile Alt Grafik Çizme

  • plt.subplot(1,2,1) # 1 satır 2 kolon olsun 1.grafiği çiz.
  • plt.plot(new_numpay1, new_numpay2, ‘r*-‘) # kırmızı * sembol
  • plt.subplot(1,2,2) # 1 satır 2 kolon olsun 2.grafiği çiz.
  • plt.plot(new_numpay1, new_numpay2, ‘g+-‘) # yeşil + sembol
import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


new_numpay1 = np.linspace(0, 10, 20) # 20 numbers between 0 and 10
new_numpay2 = new_numpay1 ** 2 # square of each number in new_numpay1
print(new_numpay2) 

plt.subplot(1, 2, 1) # 1 row, 2 columns, 1st position
plt.plot(new_numpay1, new_numpay2, 'r*-') # r is for red color + is for plus sign

plt.subplot(1, 2, 2) # 1 row, 2 columns, 2nd position
plt.plot(new_numpay2, new_numpay1, 'g+-') # g is for green color -- is for dash line

plt.show() # display the graph
Python

Grafik Çıktısı:

MatPlotLib Chart in Chart

Figure() Metodu

Grafik içinde grafik çizdirmek için,

figure(x-axis, y-axis, x-size, y-size)

  • figures = plt.figure() # figure nesnesi oluştur
  • coord = figures.add_axes([0.1, 0.1, 0.8, 0.8]) # grafik boyutları
  • coord.plot(new_numpay11, new_numpay22, ‘b’) #veri setini grafiğe dök.
import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


new_numpay11 = np.linspace(0, 10, 20) # 20 numbers between 0 and 10
new_numpay22 = new_numpay11 ** 2 # square of each number in new_numpay1
print(new_numpay22)

figures = plt.figure() # create a figure object
coord = figures.add_axes([0.1, 0.1, 0.8, 0.8]) # add axes to the figure
coord.plot(new_numpay11, new_numpay22, 'b') # b is for blue color
coord.set_xlabel('X-axis') # x-axis label
coord.set_ylabel('Y-axis') # y-axis label
coord.set_title('X vs Y Charts') # title of the graph

plt.show() # display the graphthe graph
Python

Grafik Çıktısı:

Figure Kayıt Etme İşlemi

  • fig1.savefig(“figure1.png”, dpi=200)

satırı ile proje dosyalarının bulunduğu dizine veye vereceğiniz herhangi bir dosya yoluna kayıt edecektir.

İç İçe Geçmiş Grafik Çizme

import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


new_numpay11 = np.linspace(0, 10, 20) # 20 numbers between 0 and 10
new_numpay22 = new_numpay11 ** 2 # square of each number in new_numpay1
print(new_numpay22)

figures = plt.figure() # create a figure object
coord = figures.add_axes([0.1, 0.1, 0.8, 0.8]) # add axes to the figure
coord.plot(new_numpay11, new_numpay22, 'b') # b is for blue color
coord.set_xlabel('X-axis') # x-axis label
coord.set_ylabel('Y-axis') # y-axis label
coord.set_title('Max Chart') # title of the graph

coord2 = figures.add_axes([0.2, 0.5, 0.4, 0.3]) # add axes to the figure
coord2.plot(new_numpay22, new_numpay11, 'r') # r is for red color
coord2.set_xlabel('X-axis') # x-axis label
coord2.set_ylabel('Y-axis') # y-axis label
coord2.set_title('Min Chart') # title of the graph

plt.show() # display the graph
Python
Matplotlib chart in chart method

Subplots() – Grafik Ekranını Bölme

  • (chart1, chart2) = figures.subplots(row, column)
  • (chart1, chart2) = figures.subplots(1,2) #1 satır 2 sütun grafik
  • (chart1, chart2) = figures.subplots() # tek grafik

Bu metod yardımıyla belirtilen satır ve sütun adedince alt grafik alanları oluşturulur.

import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


## Create a subplots() object
np_distance = np.linspace(0, 10, 20) # 20 numbers between 0 and 10
np_time = np_distance ** 1.3 # square of each number in new_numpay1

(fig1,ax1) = plt.subplots() # 
ax1.plot(np_distance, np_time, 'r') # r is for red color
ax1.plot(np_time, np_distance, 'g') # g is for green color

plt.show() # display the graph
Python

Grafik Çıktısı:

subplots meyhod in python matlibplot

MatPlotLib Grafik Tipleri

Scatter (Dağılımlar)

  • plt.scatter(dizi1,dizi2)
import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


new_array1 = np.linspace(0, 10, 20) # 20 numbers between 0 and 10
plt.scatter(new_array1, new_array1 ** 2, color="red", label="X^2") # scatter plot


plt.show() # display the graph
Python

Grafik Çıktısı:

Histogram (Bar) Grafikleri

  • plt.hist(numpy_dizi)
import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np
import pandas as pd


new_array2 = np.random.randn(30) # random 1000 numbers
plt.hist(new_array2, bins=10, color="orange") # histogram plot


plt.show() # display the graph
Python

Grafik Çıktısı:

ZİYARETÇİ YORUMLARI - 1 YORUM
  1. Adem Duran dedi ki:

    3 boyutlu grafikler çizen kütüphaneler var mı? Görsel yönü güçlü grafikleri python ile nasıl oluşturabilirim? Bu arada hazırladığınız içerik harika aydınlattı beni.

Bu web sitesi, bilgisayarınıza bilgi depolamak amacıyla bazı tanımlama bilgilerini kullanabilir.
Bu bilgilerin bir kısmı sitenin çalışmasında esas rolü üstlenirken bir kısmı ise kullanıcı deneyimlerinin iyileştirilmesine ve geliştirilmesine yardımcı olur.
Sitemize ilk girişinizde vermiş olduğunuz çerez onayı ile bu tanımlama bilgilerinin yerleştirilmesine izin vermiş olursunuz.
Çerez bilgilerinizi güncellemek için ekranın sol alt köşesinde bulunan mavi kurabiye logosuna tıklamanız yeterli. Kişisel Verilerin Korunması,
Gizlilik Politikası ve Çerez (Cookie) Kullanımı İlkeleri hakkında detaylı bilgi için KVKK&GDPR sayfamızı inceleyiniz.
| omersahin.com.tr |
Copyright | 2007-2025