Her bir satırın altına satırdaki kodları teker teker her bir kelimeyi açıklayarak yorum satırında anlat:
-- coding: utf-8 --
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
insurance = pd.read_csv("insurance.csv")
insurance.dtypes
insurance["sex"] = insurance["sex"].astype("category")
insurance["smoker"] = insurance["smoker"].astype("category")
insurance["region"] = insurance["region"].astype("category")
insurance.dtypes
insurance.describe()
pd.set_option("display.max_columns", 20)
insurance.describe(include="all")
LINE PLOT
Example - 1: Age of the first 10 customers
x = range(1,11)
y = insurance.iloc[0:10,0]
plt.plot(x, y, "o:r")
plt.plot(x, y, "^k:")
plt.plot(x, y, linestyle = "dashed", color="hotpink", linewidth = "5")
For the other parameters please see
help(plt.plot)
Example - 2: BMI comparison of customers in the first and second 20
x = np.arange(1,51)
y = insurance.iloc[0:50,0]
plt.title("Age of The First 50 Customers")
plt.xlabel("ID")
plt.ylabel("Age")
plt.plot(x, y)
plt.grid(color = "red", linestyle = '--', linewidth = 0.5)
plt.grid(axis = "x")
plt.grid(axis = "y")
SUB GRAPHS
plot 1: BMI of the first 20 customers
x = np.arange(1,21)
y1 = insurance.iloc[0:20,2]
plt.subplot(1, 2, 1)
#plt.subplot(2, 1, 1)
plt.plot(x,y1)
plt.xticks(x)
plt.title("The First 20 Customers")
#plot 2: BMI of the second 20 customers
y2 = insurance.iloc[20:40,2]
plt.subplot(1, 2, 2)
#plt.subplot(2, 1, 2)
plt.plot(x,y2)
plt.xticks(x)
plt.title("The first 20 customers")
plt.suptitle("BMI Comparison")
plt.tight_layout(pad=1)
BAR PLOT
mySummary = insurance.groupby("smoker")["charges"].mean()
def addLbls(x,y):
for i in range(len(x)):
plt.text(i, y[i], y[i], ha = "center")
# -*- coding: utf-8 -*-
# This line specifies that the source code file is encoded in UTF-8, allowing for special characters and non-English text.
import numpy as np
# Imports the NumPy library, which is used for numerical operations in Python.
import pandas as pd
# Imports the Pandas library, which is used for data manipulation and analysis.
import matplotlib.pyplot as plt
# Imports Matplotlib's Pyplot module, used for creating static, animated, and interactive visualizations in Python.
import seaborn as sns
# Imports the Seaborn library, which is based on Matplotlib and provides a high-level interface for drawing attractive and informative statistical graphics.
insurance = pd.read_csv("insurance.csv")
# Reads a CSV file named "insurance.csv" into a Pandas DataFrame called 'insurance'.
insurance.dtypes
# Displays the data types of each column in the 'insurance' DataFrame.
insurance["sex"] = insurance["sex"].astype("category")
# Converts the 'sex' column in the 'insurance' DataFrame to the 'category' data type, which is often more efficient for text string operations.
insurance["smoker"] = insurance["smoker"].astype("category")
# Converts the 'smoker' column in the 'insurance' DataFrame to the 'category' data type.
insurance["region"] = insurance["region"].astype("category")
# Converts the 'region' column in the 'insurance' DataFrame to the 'category' data type.
insurance.dtypes
# Displays the updated data types of each column after conversions.
insurance.describe()
# Provides summary statistics of the DataFrame, such as mean, min, max, and percentiles for numerical columns.
pd.set_option("display.max_columns", 20)
# Sets the display option in Pandas so that a maximum of 20 columns will be printed when displaying the DataFrame.
insurance.describe(include="all")
# Provides summary statistics for all columns, including categorical ones, in the DataFrame.
## LINE PLOT
# Example - 1: Age of the first 10 customers
x = range(1,11)
# Creates a range object from 1 to 10 for x-axis.
y = insurance.iloc[0:10,0]
# Selects the 'age' column values for the first 10 rows from the DataFrame for y-axis.
plt.plot(x, y, "o:r")
# Plots the age of the first 10 customers in a line plot with circles and red dotted line.
plt.plot(x, y, "^k:")
# Adds a plot with triangles in black color and dotted line style.
plt.plot(x, y, linestyle = "dashed", color="hotpink", linewidth = "5")
# Adds another plot with a dashed line in hot pink color and a linewidth of 5.
# For the other parameters please see
help(plt.plot)
# Displays help documentation for the plt.plot function to explain its different parameters.
# Example - 2: BMI comparison of customers in the first and second 20
x1 = np.arange(1,21)
# Creates a NumPy array with values from 1 to 20 for the x-axis.
y1 = insurance.iloc[0:20,2]
# Selects the 'bmi' column values for the first 20 rows for y-axis.
y2 = insurance.iloc[20:40,2]
# Selects the 'bmi' column values for the second set of 20 rows for y-axis.
plt.xticks(x1)
# Sets the ticks on the x-axis using the x1 array values.
plt.plot(x1,y1,x1,y2)
# Plots the BMI of the first 20 customers against the second 20 customers.
# Example - 3
x = np.arange(1,51)
# Creates a NumPy array with values from 1 to 50 for the x-axis.
y = insurance.iloc[0:50,0]
# Selects the 'age' column values for the first 50 rows for y-axis.
plt.title("Age of The First 50 Customers")
# Sets the title of the plot.
plt.xlabel("ID")
# Labels the x-axis as "ID".
plt.ylabel("Age")
# Labels the y-axis as "Age".
plt.plot(x, y)
# Plots the age of the first 50 customers in a line plot.
plt.grid(color = "red", linestyle = '--', linewidth = 0.5)
# Adds a grid to the plot with red dashed lines and a line width of 0.5.
# plt.grid(axis = "x")
# Un-commenting this line would add a grid only on the x-axis.
# plt.grid(axis = "y")
# Un-commenting this line would add a grid only on the y-axis.
# SUB GRAPHS
# plot 1: BMI of the first 20 customers
x = np.arange(1,21)
# Creates a NumPy array with values from 1 to 20 for the x-axis.
y1 = insurance.iloc[0:20,2]
# Selects the 'bmi' column values for the first 20 rows for y-axis.
plt.subplot(1, 2, 1)
# Creates a subplot in a 1x2 grid, selecting the first subplot.
#plt.subplot(2, 1, 1)
# Alternative subplot layout (commented out).
plt.plot(x,y1)
# Plots the BMI of the first 20 customers.
plt.xticks(x)
# Sets the ticks on the x-axis using the x values.
plt.title("The First 20 Customers")
# Sets the title of the first subplot.
#plot 2: BMI of the second 20 customers
y2 = insurance.iloc[20:40,2]
# Selects the 'bmi' column values for the second set of 20 rows.
plt.subplot(1, 2, 2)
# Creates a subplot in a 1x2 grid, selecting the second subplot.
#plt.subplot(2, 1, 2)
# Alternative subplot layout (commented out).
plt.plot(x,y2)
# Plots the BMI of the second set of 20 customers.
plt.xticks(x)
# Sets the ticks on the x-axis using the x values.
plt.title("The first 20 customers")
# Sets the title of the second subplot.
plt.suptitle("BMI Comparison")
# Sets the super-title for the entire figure containing both subplots.
plt.tight_layout(pad=1)
# Adjusts subplot parameters to give specified padding between plots.
## BAR PLOT
mySummary = insurance.groupby("smoker")["charges"].mean()
# Groups the DataFrame by 'smoker' status and calculates the mean of 'charges'.
def addLbls(x,y):
for i in range(len(x)):
plt.text(i, y[i], y[i], ha="center")
# Defines a function 'addLbls' to add labels to bars in a plot, placing text at the center of each bar.
# Example - 1
mySummary = insurance.groupby("smoker")["charges"].mean()
# Re-calculates the average charges grouped by smoker status.
plt.bar(x=mySummary.index, height=mySummary.values, color="b")
# Creates a vertical bar plot for average charges with blue bars.
plt.xlabel("Smoking")
# Labels the x-axis as "Smoking".
plt.ylabel("Charges")
# Labels the y-axis as "Charges".
addLbls(mySummary.index, mySummary.values.round(2))
# Calls 'addLbls' to add rounded labels to the bars.
# Example - 2:
plt.barh(y=mySummary.index, width=mySummary.values, color="g")
# Creates a horizontal bar plot for average charges with green bars.
# Example - 3
plt.bar(x=mySummary.index, height=mySummary.values, color="b", width = 0.95)
# Creates a vertical bar plot with specified bar width.
# Example - 4
plt.barh(y=mySummary.index, width=mySummary.values, color="r", height=0.2)
# Creates a horizontal bar plot with specified bar height.
## PIE CHART
# Example - 1
mySummary = insurance.groupby("region")["charges"].sum()
# Groups the DataFrame by 'region' and calculates the sum of 'charges'.
labels = mySummary.index
# Gets region names for pie chart labels.
vals = mySummary.values
# Gets total charges for each region.
myCols = sns.color_palette("viridis", 4)
# Generates a color palette using Seaborn with 4 colors (not used directly).
mySelection = (0, 0, 0.2, 0)
# Sets a slice offset for one of the pie chart segments to highlight it.
myCols = ['#FF9999', '#66B2FF', '#99FF99', '#FFCC99']
# Defines custom colors for the pie chart segments.
plt.pie(vals,
explode=mySelection,
labels=labels,
autopct="%4.1f%%",
shadow=True,
startangle=180,
colors=myCols)
# Draws a pie chart with specified settings, displaying percentage using 'autopct' and adding a shadow effect.
# plt.legend()
# Uncomment to add a legend to the chart.
# plt.legend(title="Regions")
# Uncomment to add a titled legend indicating regions.
## SCATTER PLOT
# Example - 1:
x = insurance.age
# Selects 'age' as x-axis data for the scatter plot.
y = insurance.bmi
# Selects 'bmi' as y-axis data for the scatter plot.
plt.scatter(x, y)
# Creates a scatter plot of age versus BMI.
plt.xlabel("Age")
# Labels the x-axis as "Age".
plt.ylabel("BMI")
# Labels the y-axis as "BMI".
mySelection = [1072, 548, 1032, 437, 154, 653, 645, 862, 25, 603]
# Sets list of specific data index positions for highlighting in a scatter plot.
mySubset = insurance.iloc[mySelection,[0,6]]
# Extracts selected rows and columns for specific ages and charges.
x = mySubset.age
# Selects 'age' as x-axis data for the new scatter plot.
y = mySubset.charges
# Selects 'charges' as y-axis data for the new scatter plot.
plt.scatter(x, y)
# Creates a scatter plot of age versus charges.
plt.xlabel("Age")
# Re-labels the x-axis as "Age" for the new plot.
plt.ylabel("Charges")
# Re-labels the y-axis as "Charges" for the new plot.
# Example - 2:
sns.scatterplot(x="age",
y="charges",
hue="smoker",
data=insurance)
# Creates a scatter plot using Seaborn with 'age' and 'charges', coloring points by the 'smoker' category.
# Example - 3
fig = plt.figure(figsize=(10, 6))
# Creates a new figure with specified width and height.
ax = plt.axes(projection ="3d")
# Adds 3D axes to the figure.
ax.scatter(insurance.age, insurance.charges, insurance.bmi, color="darkblue")
# Creates a 3D scatter plot with age, charges, and BMI data points in dark blue color.
ax.set_xlabel("Age")
# Sets label for the x-axis in 3D plot.
ax.set_ylabel("Charges")
# Sets label for the y-axis in 3D plot.
ax.set_zlabel("BMI", rotation=90)
# Sets label for the z-axis in 3D plot with rotation.
ax.zaxis.labelpad=-0.7
# Adjusts the padding for the z-axis label.
plt.title("3D-Scatter Plot")
# Sets the title for the 3D scatter plot.
# # Example - 4
pd.plotting.scatter_matrix(insurance, figsize=(20,20), grid=True, marker='o')
# Creates a scatter matrix plot for all numerical columns to visualize pairwise relationships.
# For more info about colormaps, please see:
https://matplotlib.org/stable/tutorials/colors/colormaps.html
# Provides a link to Matplotlib's colormap tutorial for more information on color maps.
## HISTOGRAM
# Example - 1
sns.histplot(data=insurance, x="bmi", color="magenta")
# Creates a histogram for the 'bmi' column with bars colored in magenta.
# Example - 2
sns.histplot(data=insurance, y="bmi", color="lime")
# Creates a horizontal histogram for the 'bmi' column with bars colored in lime.
# Example - 3
sns.histplot(data=insurance, x="bmi", color="plum", bins=8)
# Creates a histogram with 8 bins for 'bmi', using plum color.
# Example - 4
sns.histplot(data=insurance, x="bmi", color="salmon", bins=12)
# Creates a histogram with 12 bins for 'bmi', using salmon color.
# Example - 5
sns.histplot(data=insurance, x="bmi", bins=8, color="teal", kde=True)
# Creates a histogram with a kernel density estimate (KDE) overlay for 'bmi', using teal color.
# Example - 6
sns.histplot(x="bmi", kde=True, data=insurance, color="purple")
# Creates a histogram with KDE overlay for 'bmi', using purple color.
# BOX PLOT
# Example - 1
insurance["bmi"].describe().round(2)
# Generates descriptive statistics for the 'bmi' column, rounding the results to two decimal places.
bp = plt.boxplot(insurance["bmi"],
vert=True,
showmeans=True,
meanline=True,
labels=('x'),
patch_artist=True,
medianprops={'linewidth': 2, 'color': 'blue'},
meanprops={'linewidth': 2, 'color': 'magenta'},
notch=True)
# Creates a vertical box plot for the 'bmi' column, displaying mean and median lines with specified properties.
plt.ylabel("Charges")
# Sets the label for the y-axis (although this seems to be an error, as data is likely BMI, but axis is labeled as "Charges").
plt.legend([bp['medians'][0], bp['means'][0]], ['median', 'mean'])
# Adds a legend to denote lines representing the median and mean.
# Example - 2
sns.boxplot(y="smoker",
x="charges",
data=insurance,
palette="rainbow")
# Creates a horizontal box plot for 'charges' categorized by 'smoker' status, using a rainbow color palette.
# VIOLIN GRAPH
# Example - 1
sns.violinplot(y="smoker",
x="charges",
data=insurance,
palette="coolwarm")
# Creates a violin plot for 'charges' categorized by 'smoker' status using the 'coolwarm' palette.
# HEAT MAP
# Example - 1
myCors = insurance[["age", "bmi", "children", "charges"]].corr()
# Computes correlation coefficients between selected numeric columns.
sns.heatmap(
myCors,
annot = True,
square=True,
cmap="Reds"
)
# Creates a heatmap of the correlation matrix with annotations, squares cells, and uses the 'Reds' colormap.
Tabii, her adımı Türkçe olarak yorumlayayım:
python
# -*- coding: utf-8 -*-
# Bu satır, kaynak kod dosyasının UTF-8 kodlamasında olduğunu belirtir, bu sayede özel karakterler ve İngilizce olmayan metinler kullanılabilir.
import numpy as np
# NumPy kütüphanesini içe aktarır, bu kütüphane Python'da sayısal işlemler için kullanılır.
import pandas as pd
# Pandas kütüphanesini içe aktarır, bu kütüphane veri manipülasyonu ve analizi için kullanılır.
import matplotlib.pyplot as plt
# Matplotlib'in Pyplot modülünü içe aktarır, bu modül Python'da çeşitli görselleştirmeler oluşturmak için kullanılır.
import seaborn as sns
# Seaborn kütüphanesini içe aktarır, bu Matplotlib temelli bir kütüphane olup, istatistiksel grafikleri estetik ve bilgilendirici bir biçimde çizer.
insurance = pd.read_csv("insurance.csv")
# "insurance.csv" adlı CSV dosyasını 'insurance' adlı bir Pandas DataFrame'ine okur.
insurance.dtypes
# 'insurance' DataFrame'indeki her sütunun veri tiplerini gösterir.
insurance["sex"] = insurance["sex"].astype("category")
# 'insurance' DataFrame'indeki 'sex' sütununu 'category' veri tipine dönüştürür, bu genellikle metin verileri için daha verimlidir.
insurance["smoker"] = insurance["smoker"].astype("category")
# 'smoker' sütununu 'category' veri tipine dönüştürür.
insurance["region"] = insurance["region"].astype("category")
# 'region' sütununu 'category' veri tipine dönüştürür.
insurance.dtypes
# Veri tipi dönüşümünden sonra güncellenen her sütunun veri tiplerini gösterir.
insurance.describe()
# DataFrame'in sayısal sütunlarına ait özet istatistikleri, örneğin ortalama, min/max değerler ve yüzdelikler gibi bilgileri verir.
pd.set_option("display.max_columns", 20)
# Pandas'ta veri çerçevesinin gösteriminde maksimum 20 sütun gösterilecek şekilde ayarı belirler.
insurance.describe(include="all")
# DataFrame'deki tüm sütunlar için, kategorik olanlar da dahil, özet istatistikleri verir.
## ÇİZGİ GRAFİĞİ
# Örnek - 1: İlk 10 müşterinin yaşı
x = range(1,11)
# x ekseni için 1'den 10'a kadar bir aralık oluşturur.
y = insurance.iloc[0:10,0]
# DataFrame'den ilk 10 satırın 'age' sütunundaki değerleri seçer, y ekseni için.
plt.plot(x, y, "o:r")
# İlk 10 müşterinin yaşını daireler ve kırmızı kesik çizgi ile bir çizgi grafikte çizer.
plt.plot(x, y, "^k:")
# Siyah renkli üçgenler ve kesik çizgi stilinde bir grafik daha ekler.
plt.plot(x, y, linestyle="dashed", color="hotpink", linewidth="5")
# Sıcak pembe renkte ve 5 kalınlığında kesik çizgi stilinde başka bir grafik ekler.
# Diğer parametreler için lütfen bakınız
help(plt.plot)
# plt.plot fonksiyonunun çeşitli parametrelerini açıklayan yardım dokümanını görüntüler.
# Örnek - 2: İlk ve ikinci 20 müşterinin BMI karşılaştırması
x1 = np.arange(1,21)
# x ekseni için 1'den 20'ye kadar bir NumPy dizisi oluşturur.
y1 = insurance.iloc[0:20,2]
# İlk 20 satır için 'bmi' sütunu değerlerini y ekseni olarak seçer.
y2 = insurance.iloc[20:40,2]
# İkinci 20 satır için 'bmi' sütunu değerlerini y ekseni olarak seçer.
plt.xticks(x1)
# x eksenindeki işaretleri x1 dizi değerleri ile ayarlar.
plt.plot(x1, y1, x1, y2)
# İlk 20 ve ikinci 20 müşterinin BMI değerlerini bir çizgi grafikte gösterir.
# Örnek - 3
x = np.arange(1,51)
# x ekseni için 1'den 50'ye kadar bir NumPy dizisi oluşturur.
y = insurance.iloc[0:50,0]
# İlk 50 satırın 'age' sütunu değerlerini y ekseni için seçer.
plt.title("İlk 50 Müşterinin Yaşı")
# Grafiğin başlığını ayarlar.
plt.xlabel("ID")
# x eksenini "ID" etiketiyle etiketler.
plt.ylabel("Yaş")
# y eksenini "Yaş" etiketiyle etiketler.
plt.plot(x, y)
# İlk 50 müşterinin yaşını bir çizgi grafikte çizer.
plt.grid(color="red", linestyle='--', linewidth=0.5)
# Grafiğe kırmızı, kesik çizgili ve 0.5 kalınlığında bir ızgara ekler.
# plt.grid(axis = "x")
# Bu satırın yorumu kaldırılırsa sadece x ekseninde ızgara belirir.
# plt.grid(axis = "y")
# Bu satırın yorumu kaldırılırsa sadece y ekseninde ızgara belirir.
# ALT GRAFİKLER
# grafik 1: İlk 20 müşterinin BMI'si
x = np.arange(1,21)
# x ekseni için 1'den 20'ye kadar bir NumPy dizisi oluşturur.
y1 = insurance.iloc[0:20,2]
# İlk 20 satırın 'bmi' sütunu değerlerini y ekseni için seçer.
plt.subplot(1, 2, 1)
# 1x2 matrisli bir alt grafik oluşturur, ilk grafiği seçer.
#plt.subplot(2, 1, 1)
# Alternatif alt grafik düzeni (yoruma alınmış).
plt.plot(x, y1)
# İlk 20 müşterinin BMI değerlerini çizer.
plt.xticks(x)
# x eksenindeki işaretleri x değerleri ile ayarlar.
plt.title("İlk 20 Müşteri")
# İlk alt grafiğin başlığını ayarlar.
# grafik 2: İkinci 20 müşterinin BMI'si
y2 = insurance.iloc[20:40,2]
# İkinci setin 20 satırı için 'bmi' sütunu değerlerini seçer.
plt.subplot(1, 2, 2)
# 1x2 matrisli bir alt grafik oluşturur, ikinci grafiği seçer.
#plt.subplot(2, 1, 2)
# Alternatif alt grafik düzeni (yoruma alınmış).
plt.plot(x, y2)
# İkinci 20 müşterinin BMI değerlerini çizer.
plt.xticks(x)
# x eksenindeki işaretleri x değerleri ile ayarlar.
plt.title("İkinci 20 müşteri")
# İkinci alt grafiğin başlığını ayarlar.
plt.suptitle("BMI Karşılaştırması")
# Her iki alt grafik içeren şeklin üst başlığını ayarlar.
plt.tight_layout(pad=1)
# Alt grafikler arasındaki belirtilen yastıklarla ayarlama yapar.
## ÇUBUK GRAFİĞİ
mySummary = insurance.groupby("smoker")["charges"].mean()
# DataFrame'i 'smoker' durumuna göre gruplar ve 'charges' kolonunun ortalamasını hesaplar.
def addLbls(x, y):
for i in range(len(x)):
plt.text(i, y[i], y[i], ha="center")
# Çubuk grafigine merkezde etiketler ekleyen 'addLbls' adlı bir fonksiyon tanımlar.
# Örnek - 1
mySummary = insurance.groupby("smoker")["charges"].mean()
# Sigara içen duruma göre ortalama masrafları yeniden hesaplar.
plt.bar(x=mySummary.index, height=mySummary.values, color="b")
# Mavi çubuklarla ortalama masraflar için dikey bir çubuk grafik oluşturur.
plt.xlabel("Sigara Kullanımı")
# x eksenini "Sigara Kullanımı" etiketiyle etiketler.
plt.ylabel("Masraflar")
# y eksenini "Masraflar" etiketiyle etiketler.
addLbls(mySummary.index, mySummary.values.round(2))
# Çubukların üzerine yuvarlatılmış etiketler eklemek için 'addLbls' fonksiyonunu çağırır.
# Örnek - 2:
plt.barh(y=mySummary.index, width=mySummary.values, color="g")
# Yeşil çubuklarla ortalama masraflar için yatay bir çubuk grafik oluşturur.
# Örnek - 3
plt.bar(x=mySummary.index, height=mySummary.values, color="b", width=0.95)
# Belirli çubuk genişliği ile dikey bir çubuk grafik oluşturur.
# Örnek - 4
plt.barh(y=mySummary.index, width=mySummary.values, color="r", height=0.2)
# Belirli çubuk yüksekliği ile yatay bir çubuk grafik oluşturur.
## PASTA GRAFİĞİ
# Örnek - 1
mySummary = insurance.groupby("region")["charges"].sum()
# DataFrame'i 'region' durumuna göre gruplar ve 'charges' kolonunun toplamını hesaplar.
labels = mySummary.index
# Pasta grafiği etiketleri için bölge adlarını alır.
vals = mySummary.values
# Her bölgenin toplam masraf değerlerini alır.
myCols = sns.color_palette("viridis", 4)
# Seaborn'la 4 renkten oluşan bir renk paleti oluşturur (doğrudan kullanılmamış).
mySelection = (0, 0, 0.2, 0)
# Dilimlerden birini öne çıkarmak için bir kesme ofseti yapar.
myCols = ['#FF9999', '#66B2FF', '#99FF99', '#FFCC99']
# Pasta dilimleri için özel renkler tanımlar.
plt.pie(vals,
explode=mySelection,
labels=labels,
autopct="%4.1f%%",
shadow=True,
startangle=180,
colors=myCols)
# Belirtilen ayarlarla pasta grafiği çizer, yüzde gösterimi ve gölge efekti ekler.
# plt.legend()
# Yorumu kaldırılarak grafik için bir açıklama eklenebilir.
# plt.legend(title="Bölgeler")
# Yorumu kaldırılarak grafik için başlıklı bir açıklama eklenebilir.
## SAÇILIM GRAFİĞİ
# Örnek - 1:
x = insurance.age
# Saçılım grafiği için x ekseni verisi olarak 'age' sütununu seçer.
y = insurance.bmi
# Saçılım grafiği için y ekseni verisi olarak 'bmi' sütununu seçer.
plt.scatter(x, y)
# Yaş ve BMI arasında bir saçılım grafiği oluşturur.
plt.xlabel("Yaş")
# x eksenini "Yaş" etiketiyle etiketler.
plt.ylabel("BMI")
# y eksenini "BMI" etiketiyle etiketler.
mySelection = [1072, 548, 1032, 437, 154, 653, 645, 862, 25, 603]
# Belirli veri indeks pozisyonlarından oluşan bir liste oluşturur, bunlar vurgulanacak.
mySubset = insurance.iloc[mySelection, [0, 6]]
# Seçilen satır ve sütunları belirli yaşlar ve masraflar için oluşturur.
x = mySubset.age
# Yeni saçılım grafiği için x ekseni verisi olarak 'age' sütununu seçer.
y = mySubset.charges
# Yeni saçılım grafiği için y ekseni verisi olarak 'charges' sütununu seçer.
plt.scatter(x, y)
# Yaş ve masraflar arasında bir saçılım grafiği oluşturur.
plt.xlabel("Yaş")
# Yeni saçılım grafiği için x eksenini "Yaş" etiketi ile yeniden etiketler.
plt.ylabel("Masraflar")
# Yeni saçılım grafiği için y eksenini "Masraflar" etiketi ile yeniden etiketler.
# Örnek - 2:
sns.scatterplot(x="age",
y="charges",
hue="smoker",
data=insurance)
# 'age' ve 'charges' arasında Seaborn kullanarak bir saçılım grafiği oluşturur ve noktaları 'smoker' kategorisine göre renklendirir.
# Örnek - 3
fig = plt.figure(figsize=(10, 6))
# Belirtilen genişlik ve yükseklikte yeni bir figür oluşturur.
ax = plt.axes(projection="3d")
# Figüre 3D eksenler ekler.
ax.scatter(insurance.age, insurance.charges, insurance.bmi, color="darkblue")
# Yaş, masraflar ve BMI verilerini koyu mavi renkli noktalar ile 3D saçılım grafiğinde çizer.
ax.set_xlabel("Yaş")
# 3D grafikte x ekseni için etiketi ayarlar.
ax.set_ylabel("Masraflar")
# 3D grafikte y ekseni için etiketi ayarlar.
ax.set_zlabel("BMI", rotation=90)
# 3D grafikte z ekseni için etiketi ayarlar ve döndürür.
ax.zaxis.labelpad=-0.7
# z ekseni etiketi için dolgu düzenlemesi yapar.
plt.title("3D-Saçılım Grafiği")
# 3D saçılım grafiği için başlığı ayarlar.
# # Örnek - 4
pd.plotting.scatter_matrix(insurance, figsize=(20,20), grid=True, marker='o')
# Tüm sayısal sütunlar arasındaki çiftli ilişkileri görselleştirmek için bir saçılım matrisi grafiği oluşturur.
# Renk haritaları hakkında daha fazla bilgi için, lütfen bakınız:
https://matplotlib.org/stable/tutorials/colors/colormaps.html
# Renk haritaları hakkında daha fazla bilgi edinmek için Matplotlib'in ilgili öğretici bağlantısını sağlar.
## HİSTOGRAM
# Örnek - 1
sns.histplot(data=insurance, x="bmi", color="magenta")
# 'bmi' sütunu için magenta renkte çubuklarla bir histogram oluşturur.
# Örnek - 2
sns.histplot(data=insurance, y="bmi", color="lime")
# 'bmi' sütunu için lime renkte yatay bir histogram oluşturur.
# Örnek - 3
sns.histplot(data=insurance, x="bmi", color="plum", bins=8)
# 'bmi' için 8 çubukla plum renkte bir histogram oluşturur.
# Örnek - 4
sns.histplot(data=insurance, x="bmi", color="salmon", bins=12)
# 'bmi' için 12 çubukla salmon renkte bir histogram oluşturur.
# Örnek - 5
sns.histplot(data=insurance, x="bmi", bins=8, color="teal", kde=True)
# 'bmi' için kernel yoğunluk tahmini (KDE) ile birlikte teal renkte 8 çubukla bir histogram oluşturur.
# Örnek - 6
sns.histplot(x="bmi", kde=True, data=insurance, color="purple")
# 'bmi' için KDE ile birlikte purpur renkte bir histogram oluşturur.
# KUTU GRAFİĞİ
# Örnek - 1
insurance["bmi"].describe().round(2)
# 'bmi' sütunu için açıklayıcı istatistikler oluşturur, sonuçları virgülden sonra iki basamak olacak şekilde yuvarlar.
bp = plt.boxplot(insurance["bmi"],
vert=True,
showmeans=True,
meanline=True,
labels=('x'),
patch_artist=True,
medianprops={'linewidth': 2, 'color': 'blue'},
meanprops={'linewidth': 2, 'color': 'magenta'},
notch=True)
# 'bmi' sütunu için ortalama ve medyan çizgilerini gösteren belirtilen özelliklerle dikey bir kutu grafiği oluşturur.
plt.ylabel("Masraflar")
# y eksenini etiketler (veri muhtemelen BMI iken etiket "Masraflar" olarak belirlenmiş, bu bir hata olabilir).
plt.legend([bp['medians'][0], bp['means'][0]], ['medyan', 'ortalama'])
# Medyan ve ortalamayı temsil eden çizgiler için bir başlık ekler.
# Örnek - 2
sns.boxplot(y="smoker",
x="charges",
data=insurance,
palette="rainbow")
# 'charges' ve 'smoker' durumu temelinde gökkuşağı renk paleti kullanarak yatay bir kutu grafiği oluşturur.
# VİYOLİN GRAFİĞİ
# Örnek - 1
sns.violinplot(y="smoker",
x="charges",
data=insurance,
palette="coolwarm")
# 'smoker' durumuna göre 'charges' için 'coolwarm' paleti kullanarak bir viyola grafiği oluşturur.
# ISI HARİTASI
# Örnek - 1
myCors = insurance[["age", "bmi", "children", "charges"]].corr()
# Seçilen sayısal sütunlar arasındaki korelasyon katsayılarını hesaplar.
sns.heatmap(
myCors,
annot=True,
square=True,
cmap="Reds"
)
# Korelasyon matrisinin anotlar ve kare hücrelerle birlikte 'Reds' renk haritasını kullanarak bir ısı haritasını oluşturur.