카테고리 없음

[Pandas] How to Draw Violin Plots & Scatter Plots Using Seaborn

레야_Reya 2024. 4. 2. 15:13

 

Let's practice drawing different types plots using Seaborn library.

 

Violin plots

 

Violin plots are handy when you want to visualize the distribution of numeric data

across different categories.

 

1. Import Libraries

You need seaborn for creating the plots, and matplotlib will be optionally used

to customize the plots further. Let's import both libraries.

import seaborn as sns
import matplotlib.pyplot as plt

 

2. Load Dataset

We will use seaborn's built-in dataset named 'tips'.

tips = sns.load_dataset('tips')

 

3. Draw the Violin Plot

You can create a violin plot using violinplot().

sns.violinplot(x='time', y='total_bill', data=tips)

 

4. Customizing Options

You can customize your plot by setting colors, linewidths, styles, axis labels, etc.

Here is an example. I added title, labels of x-axis and y-axis, set palette color, and adjusted line width.

sns.violinplot(x='time',y='total_bill', hue='sex', data=tips, palette='Set3', linewidth=2)

plt.title('Distribution of Total Bill Amount by Time of Day')
plt.xlabel('Time of Day')
plt.ylabel('Total Bill Amount')

The violin plot above displays distributions of total bill amounts against time of day.

The violins and data points will be colored differently for 'Male' and 'Female'.

📌 "Hue" parameter in seaborn :
This is useful when you want to add an additional categorical variable to your plot.
You can group the variable values and color the data points in the plot accordingly.

 

 

 

Scatter Plots

 

One way to draw scatter plots is using scatterplot() function.

sns.scatterplot(x="total_bill", y="tip", hue="time", data=tips)

 

 

 

Another way is to use lmplot() function as demonstrated below.

📌 lmplot() function in seaborn :
It is used to easily create scatter plots with linear regression fits.
sns.lmplot(x='total_bill', y='tip', hue='sex', col='time', data=tips,
          scatter_kws={'color': 'red', 's': 50, 'alpha': 0.5}, lowess=True)

 

When you set the lowess parameter to True in seaborn's lmplot() function,

it fits a lowess regression curve to the scatter plot instead of the default linear regression line.

This allows you to visually inspect the relationship between the variables in a more flexible manner.

📌 "lowess" parameter :
If you set lowess=True, seaborn will fit a lowess regression curve to the scatter plot,
allowing you to see the non-linear relationship between the variables.

 

 

 

Here is one more example on drawing scatter plots with lmplot() function.

scatter1 = sns.lmplot(x='total_bill', y='tip', data=tips, fit_reg=False, 
                      hue='sex', markers=['o','x'], scatter_kws={'alpha':0.5})

 

📌 "fit_reg" parameter :
By setting fit_reg=False, no regression line is displayed on the scatter plot.

 

 

 

 


🔍   Today's Review..  

<Do it! 데이터 분석을 위한 판다스 입문> 교재의 4-3강을 Jupiter Notebook 에서 실습해보며 영어로 주요 내용을 정리해보았다. 영어로 정리하면 API를 보면서 한번 더 정확하게 플롯의 개념들을 공부할 수 있다는 장점이 있다.👍🏻

 

위에 정리한 바이올린플롯과 산점도 그래프 외에도 교재를 통해 히스토그램부터 distplot, regplot, countplot, jointplot, kdeplot 메서드 등 다양한 함수를 이용해 그래프들을 그려볼 수 있다.

하지만 결국 실무에서 자주 쓰이는 그래프들은 따로 있고, 나중에 자연스레 익숙해질 것이기 때문에 모든 그래프를 다 자유자재로 다루기 위해 모든 함수와 파라미터를 정확히 알고 있어야 할 필요는 없다고 생각한다.

어떤 그래프를 그릴 수 있는지 그 종류를 알고 있고, 데이터로 이런 표현들이 가능하다는 점만 알고 있다면 세부적인 파라미터 값들은 그때 그때 필요한 내용을 Seaborn API reference documentation 에서 찾아보면 된다.

 

가장 중요한 건 항상 궁금증 가지기! 모르는 건 찾아보고 직접 써보는 습관을 들이는 것이 좋은 자세라고 생각한다.😊