Показаны сообщения с ярлыком sns-plt. Показать все сообщения
Показаны сообщения с ярлыком sns-plt. Показать все сообщения

вторник, 9 мая 2023 г.

Несколько графиков Seaborn через plt.subplots

fig, ax =  plt.subplots(1, 2, figsize=(18, 5))
sns.histplot(data=df, x='seats', kde=True, ax=ax[0])
sns.kdeplot(data=df, x='seats', hue='category', ax=ax[1])
plt.show()

Seaborn - stripplot

stripplot() — ещё один способ отображения категориальных данных. Для каждой категории получаем диаграмму рассеяния. График рекомендуют строить в сочетании с другими, например с violinplot() 

Документация - https://seaborn.pydata.org/generated/seaborn.stripplot.html
tips = sns.load_dataset("tips")
sns.stripplot(data=tips, x="total_bill", y="day", hue="sex")

Seaborn - violinplot

Как и boxplot(), этот график характеризует форму распределения. Необычный внешний вид получается из-за сложения двух графиков плотности распределения. Основное преимущество перед boxplot() — возможность изучить распределение и установить его тип. 

Документация - https://seaborn.pydata.org/generated/seaborn.violinplot.html
df = sns.load_dataset("titanic")
sns.violinplot(x=df["age"])

#sns.violinplot(data=df, x="age", y="class")
#sns.violinplot(data=df, x="class", y="age", hue="alive")


Seaborn - pairplot, scatterplot, relplot

Plot pairwise relationships in a dataset. Документация - https://seaborn.pydata.org/generated/seaborn.pairplot.html
penguins = sns.load_dataset("penguins")
sns.pairplot(penguins)

#sns.pairplot(penguins, hue="species")
#sns.pairplot(penguins, hue="species", diag_kind="hist")
#sns.pairplot(penguins, kind="kde")

g = sns.pairplot(penguins, diag_kind="kde")
g.map_lower(sns.kdeplot, levels=4, color=".2")

Draw a scatter plot with possibility of several semantic groupings. 
Документация - https://seaborn.pydata.org/generated/seaborn.scatterplot.html

sns.scatterplot(data=tips, x="total_bill", y="tip", hue="size")
Figure-level interface for drawing relational plots onto a FacetGrid. This function provides access to several different axes-level functions that show the relationship between two variables with semantic mappings of subsets.  
Документация - https://seaborn.pydata.org/generated/seaborn.relplot.html

sns.relplot(data=tips, x="total_bill", y="tip", hue="day", col="time")

График распределения одной величины - distplot

Документация - https://seaborn.pydata.org/generated/seaborn.distplot.html
import seaborn as sns
sport = sns.load_dataset('exercise')
sns.distplot(sport['pulse']) 
distplot устаревшая функция вместо нее вводят
  • https://seaborn.pydata.org/generated/seaborn.histplot.html
  • https://seaborn.pydata.org/generated/seaborn.displot.html - This function provides access to several approaches for visualizing the univariate or bivariate distribution of data, including subsets of data defined by semantic mapping and faceting across multiple subplots. примеры:
penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, x="flipper_length_mm")

#sns.histplot(data=penguins, x="flipper_length_mm", bins=30)
#sns.histplot(data=penguins, x="flipper_length_mm", kde=True)
#sns.histplot(data=penguins, x="flipper_length_mm", hue="species")
иллюстрация с использованием hue

Seaborn boxplot - ящик с усами

Помимо осех X,Y добавлено третье измерение через раскраску hue
import seaborn as sns
from numpy import median

sport = sns.load_dataset('exercise')
ax = sns.boxplot(x='kind', y='pulse', hue='diet', data=sport)



Графический смысл диаграммы размаха:



Цветовые палитры в seaborn

В seaborn реализована поддержка цветовых палитр. Доступ к ним получают методом color_palette() (англ. «цветовая палитра»): 
current_palette = sns.color_palette('coolwarm', 20)
print(sns.palplot(current_palette)) 

Документация Choosing color palettes 

https://seaborn.pydata.org/generated/seaborn.set_theme.html
Set aspects of the visual theme for all matplotlib and seaborn plots. By default, seaborn plots will be made with the current values of the matplotlib rcParams. Calling this function with no arguments will activate seaborn’s “default” theme.
https://seaborn.pydata.org/generated/seaborn.axes_style.html
Get the parameters that control the general style of the plots. Calling with no arguments will return the current defaults for the style parameters. Calling with the name of a predefined style will show those parameter values. Use the function as a context manager to temporarily change the style of your plots.
https://seaborn.pydata.org/generated/seaborn.set_style.html
Set the parameters that control the general style of the plots. Call the function with the name of a seaborn style to set the default for all plots. You can also selectively override seaborn’s default parameter values.
Стиль графика задают методом set_style(). Существует пять разных тем: 'darkgrid' — тёмная сетка; 'whitegrid' — белая сетка; 'dark' — тёмный; 'white' — белый; 'ticks' — штриховка. По умолчанию установлена тема 'darkgrid'. Если вам не нужна сетка на графике, подключите тему 'dark', 'white' или 'ticks'. 

https://seaborn.pydata.org/generated/seaborn.plotting_context.html - Get the parameters that control the scaling of plot elements. etc.

matplotlib стили и использование

Посмотреть какие стили доступны в matplotlib
import matplotlib.pyplot as plt
print(plt.style.available) # вызовем разные наборы цветов 
Использовать один из приведенных стилей с помощью контекстного менеджера with
with plt.style.context('seaborn-pastel'):
    plt.bar([10, 20, 30, 40],[3, 9, 18, 7])
Если все графики должны быть оформлены в едином стиле, в начале проекта вызовите метод plt.style.use()
plt.style.use('ggplot') # здесь выбран стиль ggplot
документация Customizing Matplotlib with style sheets and rcParams

Seaborn barplot

Документация по barplot доступна здесь.
Метод barplot() самостоятельно агрегирует данные и по умолчанию считает среднее. Этой опцией управляют параметром estimator.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

flights = sns.load_dataset('flights')

sns.set_style('whitegrid')
ax = sns.barplot(x='year', y='passengers', data=flights, estimator=np.mean) 

plt.show()
display(flights.head())
Вот реализация столбчатой диаграммы через matplotlib для предыдущего примеры
import matplotlib.pyplot as plt
import pandas as pd
tmp = flights.groupby('year')[['passengers']].mean().reset_index()
with plt.style.context('seaborn'):
    plt.bar(tmp['year'], tmp['passengers'])
    plt.show()

Seaborn встроенные датасеты

Посмотреть на список встроенных датасетов можно вызовом get_dataset_names(), загрузить вызовом load_dataset()
import seaborn as sns

display(sns.get_dataset_names())
titanic = sns.load_dataset('titanic')
display(titanic.head())
seaborn.load_dataset

понедельник, 8 мая 2023 г.

Seaborn jointplot

jointplot совмещает графики распраделения двух величин и диаграмму рассеяния scatter
# совместное распределения и график корреляции
sns.set_style('darkgrid')
sns.jointplot(x='age', y='fare', data=titanic) 

#sns.jointplot(x='rating', y='tips', data=taxi, kind='reg', color='#006400')  # плотность распределения и регрессию