1679614260
Trong bài viết này, chúng ta hãy cùng nhau tìm hiểu Seaborn bằng Python hoàn chỉnh cho người mới bắt đầu. Seaborn là một thư viện trực quan hóa dữ liệu tuyệt vời để vẽ biểu đồ thống kê bằng Python . Nó cung cấp các kiểu và bảng màu mặc định đẹp mắt để làm cho biểu đồ thống kê hấp dẫn hơn. Nó được xây dựng dựa trên thư viện matplotlib và cũng được tích hợp chặt chẽ với cấu trúc dữ liệu pandas. Trong hướng dẫn này, chúng ta sẽ xem cách sử dụng seaborn để tạo nhiều ô khác nhau và cách chúng ta có thể sử dụng nó cùng với matplotlib để làm cho các ô của chúng ta hấp dẫn hơn.
Trước khi sử dụng Seaborn, chúng ta cần cài đặt nó và sau đây tôi sẽ chỉ cho bạn một số cách để cài đặt nó trên máy tính của bạn.
Sử dụng Trình cài đặt Pip
pip là một hệ thống quản lý gói tiêu chuẩn trên thực tế được sử dụng để cài đặt và quản lý các gói phần mềm được viết bằng Python.
cài đặt pip seaborn
Sử dụng Anaconda
Anaconda là trình quản lý gói, trình quản lý môi trường và bản phân phối Python chứa một tập hợp nhiều gói nguồn mở. Nếu bạn cần các gói bổ sung sau khi cài đặt Anaconda, bạn có thể sử dụng trình quản lý gói Anaconda hoặc conda để cài đặt các gói này.
conda cài đặt seaborn
Bạn cũng có thể cài đặt phiên bản phát triển của Seaborn trực tiếp từ GitHub bằng lệnh này từ dấu nhắc lệnh.
cài đặt pip git+https://github.com/mwaskom/seaborn.git#egg=seaborn
Ngoài ra, hãy đảm bảo rằng bạn đã cài đặt các phần phụ thuộc sau trên máy tính của mình:
Tham khảo các khóa học về seaborn python để hiểu thêm về seaborn.
Trong phần này, chúng ta sẽ xem cách nhập bộ dữ liệu tích hợp sẵn của seaborn được tự động tải xuống khi cài đặt. Bạn cũng có thể sử dụng Pandas để nhập bất kỳ tập dữ liệu nào, nhưng sử dụng tập dữ liệu tích hợp có thể rất hữu ích khi thực hành Seaborn. Đây là cách chúng tôi có thể lấy danh sách tất cả các bộ dữ liệu được tích hợp trong Seaborn
import pandas
import matplotlib
import scipy
import seaborn as sns
print(sns.get_dataset_names())
Output:
['anagrams', 'anscombe', 'attention', 'brain_networks',
'car_crashes', 'diamonds', 'dots', 'exercise', 'flights',
'fmri', 'gammas', 'geyser', 'iris', 'mpg', 'penguins',
'planets', 'tips', 'titanic']
Bây giờ, hãy nhập bất kỳ bộ dữ liệu nào trong số này và trực quan hóa dữ liệu trong các phần tiếp theo.
import seaborn as sns
df = sns.load_dataset('car_crashes')
print(df.head())
Output:
total speeding alcohol ... ins_premium ins_losses abbrev
0 18.8 7.332 5.640 ... 784.55 145.08 AL
1 18.1 7.421 4.525 ... 1053.48 133.93 AK
2 18.6 6.510 5.208 ... 899.47 110.35 AZ
3 22.4 4.032 5.824 ... 827.34 142.39 AR
4 12.0 4.200 3.360 ... 878.41 165.63 CA
Chúng tôi sử dụng hình ảnh trực quan để thu thập thông tin chi tiết từ một lượng lớn dữ liệu hoặc trình bày thông tin chi tiết của mình cho các bên liên quan và việc làm cho những hình ảnh trực quan này trở nên thú vị hơn chắc chắn có thể giúp ích cho cả hai việc này. Mọi người có nhiều khả năng tập trung vào hình ảnh trực quan đẹp và hấp dẫn hơn là đồ họa nhàm chán, vì vậy phong cách có thể được coi là một thành phần quan trọng của hình ảnh hóa dữ liệu.
Thư viện Matplotlib có khả năng tùy biến cao, nhưng chúng tôi có thể khó điều chỉnh cài đặt phù hợp để có được một cốt truyện đẹp mắt và hấp dẫn. Không giống như Matplotlib, Seaborn đi kèm với các chủ đề tùy chỉnh và giao diện cấp cao để tùy chỉnh và kiểm soát sự xuất hiện của các số liệu Matplotlib.
Trước tiên, hãy xem cách chúng ta có thể định kiểu một biểu đồ Matplotlib đơn giản bằng cách sử dụng hàm set() của Seaborn.
from matplotlib import pyplot as plt
import seaborn as sns
plt.scatter(df.speeding,df.alcohol)
plt.show()
Lối ra:
Bây giờ hãy xem cách chúng ta có thể tạo kiểu cho biểu đồ này bằng cách sử dụng hàm set()
from matplotlib import pyplot as plt
import seaborn as sns
plt.scatter(df.speeding,df.alcohol)
sns.set()
plt.show()
Lối ra:
Hai hình trên cho thấy sự khác biệt trong các ô Matplotlib và Seaborn tiêu chuẩn. Việc biểu diễn dữ liệu là như nhau, nhưng có một chút khác biệt trong phong cách của các biểu đồ này.
Seaborn hỗ trợ một số chủ đề có thể giúp tạo kiểu cho đồ họa của bạn thực sự dễ dàng và giúp bạn tiết kiệm rất nhiều thời gian. Sử dụng hàm set_style() của Seaborn, chúng ta có thể đặt bất kỳ chủ đề nào có sẵn trong thư viện của Seaborn. Dưới đây là một số chủ đề phổ biến:
Hãy thử áp dụng các chủ đề này và xem chúng khác nhau như thế nào. Chủ đề cốt truyện mặc định sẽ là Darkgrid mà chúng ta đã thấy trong ví dụ trước.
from matplotlib import pyplot as plt
import seaborn as sns
plt.scatter(df.speeding,df.alcohol)
sns.set_style("whitegrid")
plt.show()
from matplotlib import pyplot as plt
import seaborn as sns
plt.scatter(df.speeding,df.alcohol)
sns.set_style("dark")
plt.show()
from matplotlib import pyplot as plt
import seaborn as sns
plt.scatter(df.speeding,df.alcohol)
sns.set_style("white")
plt.show()
from matplotlib import pyplot as plt
import seaborn as sns
plt.scatter(df.speeding,df.alcohol)
sns.set_style("ticks")
plt.show()
Nhưng chúng tôi thường không tạo các biểu đồ của mình giống như biểu đồ ở trên vì chúng tôi không bao gồm các gai trục trên cùng và bên phải. Chúng ta có thể loại bỏ các gai khỏi trục trên cùng và bên phải bằng cách sử dụng hàm despine().
from matplotlib import pyplot as plt
import seaborn as sns
plt.scatter(df.speeding,df.alcohol)
sns.set_style("ticks")
sns.despine()
plt.show()
Nhưng việc chỉ có một số chủ đề hạn chế có thể không tuyệt lắm vì chúng tôi luôn muốn có một số chủ đề linh hoạt. Hãy ghi nhớ điều đó, các kiểu này có thể tùy chỉnh và có thể được tùy chỉnh bằng cách chuyển một từ điển các tham số cho hàm set_style() của thư viện Seaborn. Các tham số khả dụng được hiển thị bằng cách sử dụng hàm axis_style() như hình bên dưới:
import seaborn as sns
param=sns.axes_style()
param
Output:
{'axes.axisbelow': True,
'axes.edgecolor': '.15',
'axes.facecolor': 'white',
'axes.grid': False,
'axes.labelcolor': '.15',
'axes.spines.bottom': True,
'axes.spines.left': True,
'axes.spines.right': True,
'axes.spines.top': True,
'figure.facecolor': 'white',
'font.family': ['sans-serif'],
'font.sans-serif': ['Arial',
'DejaVu Sans',
'Liberation Sans',
'Bitstream Vera Sans',
'sans-serif'],
'grid.color': '.8',
'grid.linestyle': '-',
'image.cmap': 'rocket',
'lines.solid_capstyle': 'round',
'patch.edgecolor': 'w',
'patch.force_edgecolor': True,
'text.color': '.15',
'xtick.bottom': True,
'xtick.color': '.15',
'xtick.direction': 'out',
'xtick.top': False,
'ytick.color': '.15',
'ytick.direction': 'out',
'ytick.left': True,
'ytick.right': False}
Thay đổi giá trị của bất kỳ tham số nào trong số này sẽ thay đổi kiểu của cốt truyện, vì vậy chúng ta có thể thử nhiều thứ để làm cho cốt truyện của mình thực sự khác biệt và hấp dẫn.
from matplotlib import pyplot as plt
import seaborn as sns
plt.scatter('speeding','alcohol',data=df)
sns.set_style("darkgrid", {'grid.color': '.5'})
sns.despine()
plt.show()
Seaborn cũng cho phép chúng tôi kiểm soát các thành phần riêng lẻ trong biểu đồ của mình, vì vậy chúng tôi có thể kiểm soát tỷ lệ của các thành phần này hoặc biểu đồ bằng cách sử dụng hàm set_context(). Chúng tôi có bốn mẫu được xác định trước cho bối cảnh, dựa trên kích thước tương đối, bối cảnh được đặt tên như sau
Theo mặc định, ngữ cảnh được đặt thành sổ ghi chép và tất cả các ví dụ ở trên đều có ngữ cảnh được đặt thành 'sổ tay'. Bây giờ, hãy thử bất kỳ bối cảnh nào khác và xem nó ảnh hưởng đến biểu đồ của chúng ta như thế nào.
from matplotlib import pyplot as plt
import seaborn as sns
plt.scatter(df.speeding,df.alcohol)
sns.set_style("dark")
sns.set_context("notebook")
plt.show()
from matplotlib import pyplot as plt
import seaborn as sns
plt.scatter(df.speeding,df.alcohol)
sns.set_style("dark")
sns.set_context("poster")
plt.show()
Seaborn nổi tiếng với việc làm cho cốt truyện và đồ họa trở nên hấp dẫn hơn bằng cách sử dụng màu sắc và sự kết hợp màu sắc hấp dẫn. Trong trực quan hóa dữ liệu, nhất thiết phải có màu sắc và màu sắc ảnh hưởng đến người quan sát chúng. Màu sắc đóng một vai trò quan trọng hơn bất kỳ khía cạnh nào khác trong trực quan hóa. Khi được sử dụng hiệu quả, màu sắc sẽ tăng thêm giá trị cho biểu đồ. Bảng màu có nghĩa là một bề mặt phẳng mà họa sĩ sắp xếp và pha trộn các loại sơn trên đó. Ở đây tôi sẽ giới thiệu cho bạn một số bảng màu trong số 170 bảng màu do Seaborn cung cấp.
sns.palplot(sns.color_palette("deep", 10))
sns.palplot(sns.color_palette("PiYG", 10))
sns.palplot(sns.color_palette("GnBu", 10))
Dưới đây là danh sách các bảng màu mà bạn có thể tự mình thử. Bạn sẽ thấy rất nhiều cách sử dụng các bảng màu này trong một vài biểu đồ tiếp theo.
'Accent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG',
'BrBG_r', 'BuGn', 'BuGn_r', 'BuPu', 'BuPu_r', 'CMRmap',
'CMRmap_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r',
'Greens', 'Greens_r', 'Greys', 'Greys_r', 'OrRd',
'OrRd_r', 'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r',
'Paired', 'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2',
'Pastel2_r', 'PiYG', 'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r',
'PuBu_r', 'PuOr', 'PuOr_r', 'PuRd', 'PuRd_r', 'Purples',
'Purples_r', 'RdBu', 'RdBu_r', 'RdGy', 'RdGy_r', 'RdPu',
'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn', 'RdYlGn_r',
'Reds', 'Reds_r', 'Set1', 'Set1_r', 'Set2', 'Set2_r',
'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'Wistia',
'Wistia_r', 'YlGn', 'YlGnBu', 'YlGnBu_r', 'YlGn_r',
'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r', 'afmhot',
'afmhot_r', 'autumn', 'autumn_r', 'binary', 'binary_r',
'bone', 'bone_r', 'brg', 'brg_r', 'bwr', 'bwr_r', 'cividis',
'cividis_r', 'cool', 'cool_r', 'coolwarm', 'coolwarm_r',
'copper', 'copper_r', 'cubehelix', 'cubehelix_r', 'flag',
'flag_r', 'gist_earth', 'gist_earth_r', 'gist_gray',
'gist_gray_r', 'gist_heat', 'gist_heat_r', 'gist_ncar',
'gist_ncar_r', 'gist_rainbow', 'gist_rainbow_r',
'gist_stern', 'gist_stern_r', 'gist_yarg', 'gist_yarg_r',
'gnuplot', 'gnuplot2','gnuplot2_r', 'gnuplot_r',
'gray', 'gray_r', 'hot', 'hot_r', 'hsv',
'hsv_r', 'icefire', 'icefire_r', 'inferno', 'inferno_r', 'jet',
'jet_r', 'magma', 'magma_r', 'mako', 'mako_r',
Trong phần này, chúng ta sẽ khám phá một số tùy chọn trong số nhiều tùy chọn mà bạn có khi sử dụng Seaborn để vẽ biểu đồ. Có một số loại cốt truyện được hỗ trợ trong Seaborn và ở đây chúng ta sẽ khám phá một số trong số chúng.
Thư viện Seaborn cung cấp cho chúng ta hàm relplot() và hàm này cung cấp quyền truy cập vào một số hàm cấp trục khác nhau hiển thị mối quan hệ giữa hai biến với ánh xạ ngữ nghĩa tập hợp con. Tham số loại chọn chức năng cấp trục bên dưới để sử dụng:
Giá trị mặc định cho loại tham số là 'phân tán', có nghĩa là theo mặc định, hàm này sẽ trả về một biểu đồ phân tán. Dưới đây là một số ví dụ về chức năng này:
import seaborn as sns
tips = sns.load_dataset("tips")
tips.head()
sns.relplot(data=tips, x="total_bill", y="tip")
sns.relplot(data=tips, x="total_bill", y="tip", hue="day")
Sử dụng tham số màu sắc
sns.relplot(data=tips, x="total_bill", y="tip", hue="sex", col="day", col_wrap=2)
sns.relplot(data=tips, x="size", y="tip",kind="line",ci=None)
Sử dụng kind=line để vẽ biểu đồ đường
Bây giờ, như bạn có thể thấy, chúng ta đã thêm một chiều bổ sung vào biểu đồ của mình bằng cách tô màu các điểm theo biến thứ ba. Ở seaborn, điều này được gọi là “ngữ nghĩa màu sắc”, bởi vì màu sắc của dấu chấm được đưa ra ý nghĩa và được thực hiện bằng cách chuyển biến thứ ba cho tham số màu sắc của hàm relplot. Chúng ta sẽ thảo luận về tham số col sau trong phần facetGrid.
Biểu đồ biểu thị phân phối dữ liệu bằng cách tạo các hộp dọc theo phạm vi dữ liệu và sau đó vẽ các thanh để hiển thị số lượng quan sát rơi vào mỗi hộp. Trong Seaborn, chúng tôi sử dụng hàm distplot() để vẽ biểu đồ. Ví dụ:
import seaborn as sns
from matplotlib import pyplot as plt
df = sns.load_dataset('iris')
sns.distplot(df['petal_length'],kde = False)
Seaborn hỗ trợ nhiều loại biểu đồ thanh và bạn sẽ thấy một số loại biểu đồ ở đây. Ở đây, như đã đề cập trong phần giới thiệu, chúng tôi sẽ sử dụng seaborn và matplotlib cùng nhau để minh họa các biểu đồ khác nhau.
Biểu đồ barplot dưới đây cho thấy những người sống sót sau vụ tai nạn Titanic theo danh mục.
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('paper')
# load dataset
titanic = sns.load_dataset('titanic')
# create plot
sns.barplot(x = 'embark_town', y = 'age', data = titanic,
palette = 'PuRd',ci=None
)
plt.legend()
plt.show()
print(titanic.columns)
import matplotlib.pyplot as plt
import seaborn as sns
# load dataset
titanic = sns.load_dataset('titanic')
# create plot
sns.barplot(x = 'sex', y = 'survived', hue = 'class', data = titanic,
palette = 'PuRd',
order = ['male', 'female'],
capsize = 0.05,
saturation = 8,
errcolor = 'gray', errwidth = 2,
ci = 'sd'
)
plt.legend()
plt.show()
Để vẽ đồ thị theo chiều ngang, hãy chuyển 'h' vào tham số phía đông của hàm barplot như hình bên dưới:
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('paper')
sns.barplot(x = 'age', y = 'embark_town', data = titanic,
palette = 'PuRd', orient = 'h',
)
plt.show()
Biểu đồ đếm có thể được coi là một biểu đồ trên một biến phân loại. Ví dụ dưới đây minh họa biểu đồ đếm
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('paper')
# load dataset
titanic = sns.load_dataset('titanic')
# create plot
sns.countplot(x = 'class', hue = 'who', data = titanic, palette = 'magma')
plt.title('Survivors')
plt.show()
Biểu đồ dấu chấm được sử dụng để hiển thị ước tính dấu chấm và khoảng tin cậy bằng cách sử dụng biểu tượng biểu đồ phân tán. Biểu đồ dấu chấm vẽ một ước tính về xu hướng trung tâm cho một biến số theo vị trí của các điểm trên biểu đồ phân tán và cung cấp một số dấu hiệu về sự không chắc chắn xung quanh ước tính đó bằng cách sử dụng các thanh lỗi.
Biểu đồ chấm có thể hữu ích hơn biểu đồ thanh để tập trung vào so sánh giữa các cấp độ khác nhau của một hoặc nhiều biến phân loại. Dưới đây là một số ví dụ về ô chấm:
# importing required packages
import seaborn as sns
import matplotlib.pyplot as plt
# loading dataset
data = sns.load_dataset("tips")
sns.pointplot(x="day", y="tip", data=data)
plt.show()
sns.pointplot(x="time", y="total_bill", hue="smoker",
data=data, palette="Accent")
Biểu đồ chung vẽ một biểu đồ hai biến với các biểu đồ hai biến và một biến. Nó sử dụng biểu đồ phân tán và biểu đồ. Biểu đồ chung cũng có thể hiển thị dữ liệu bằng Ước tính mật độ hạt nhân (KDE) và Hình lục giác. Chúng ta cũng có thể vẽ một đường hồi quy trên biểu đồ phân tán. Dưới đây là một số ví dụ về một cốt truyện chung
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style("dark")
tips=sns.load_dataset('tips')
sns.jointplot(x='total_bill', y='tip',data=tips)
# Add regression line to scatter plot and kernel density estimate to histogram
sns.jointplot(x='total_bill', y='tip', data=tips, kind='reg')
# Display kernel density estimate instead of scatter plot and histogram
sns.jointplot(x='total_bill', y='tip', data=tips, kind='kde')
# Display hexagons instead of points in scatter plot
sns.jointplot(x='total_bill', y='tip', data=tips, kind='hex')
Regplot là một trong những chức năng trong Seaborn được sử dụng để trực quan hóa mối quan hệ tuyến tính được xác định bằng hồi quy. Ngoài ra, bạn sẽ thấy một phần được tô bóng nhẹ xung quanh đường hồi quy cho biết mức độ trải rộng của các điểm trên một khu vực nhất định. Dưới đây là một số ví dụ
Bây giờ, hãy vẽ một biến rời rạc x và thêm một số jitter. Ở đây, bạn có thể thấy rằng các khu vực có nhiều điểm có mật độ dân số cao hơn có phần được tô bóng ít hơn xung quanh đường hồi quy và phần được tô bóng trải rộng hơn ở những nơi có nhiều điểm phân tán hơn.
import seaborn as sns
tips = sns.load_dataset("tips")
ax = sns.regplot(x="total_bill", y="tip", data=tips)
sns.regplot(x="size", y="total_bill", data=tips, x_jitter=0.1)
Chúng ta có thể đặt tham số ci=None để chỉ lấy dòng mà không có bất kỳ phần nào được đánh dấu.
import seaborn as sns
tips = sns.load_dataset("tips")
ax = sns.regplot(x="total_bill", y="tip", data=tips,ci=None)
Trong Seaborn, chúng ta cũng có thể sử dụng lmplot thay vì regplot để trực quan hóa hồi quy giữa hai biến như chúng ta đã thấy trong ví dụ trước. Nhưng sự khác biệt giữa hai đợt là gì?
Hàm regplot thực hiện biểu đồ và mô hình hồi quy tuyến tính phù hợp đơn giản, trong khi hàm lmplot kết hợp regplot và FacetGrid.
Lớp FacetGrid giúp bạn trực quan hóa việc phân phối một biến cũng như mối quan hệ giữa nhiều biến một cách riêng biệt trong các tập hợp con của tập dữ liệu của bạn bằng cách sử dụng nhiều ngăn.
Cũng cần lưu ý rằng lmplot() chuyên sâu hơn về mặt tính toán và được dự định là một giao diện thuận tiện để khớp các mô hình hồi quy trên các tập hợp con có điều kiện của tập dữ liệu.
Đây là một ví dụ lmplot đơn giản mà nó dường như hoạt động chính xác như regplot.
import seaborn as sns
tips = sns.load_dataset("tips")
sns.lmplot(x="total_bill", y="tip", data=tips)
Đây là cách chúng ta có thể sử dụng các tính năng nâng cao của lmplot() và sử dụng nó với lưới nhiều ô để vẽ các mối quan hệ có điều kiện.
sns.lmplot(x="total_bill", y="tip", col="day", hue="day",
data=tips, col_wrap=2, height=3)
Biểu đồ KDE là Ước tính mật độ hạt nhân được sử dụng để trực quan hóa Mật độ xác suất của các biến dữ liệu liên tục hoặc không tham số, tức là chúng ta có thể vẽ biểu đồ cho biến đơn biến hoặc nhiều biến. Dưới đây là một số ví dụ
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style("dark")
iris = sns.load_dataset("iris")
# Plotting the KDE Plot
sns.kdeplot(iris.loc[(iris['species']=='setosa'),
'sepal_length'], color='b', shade=True, Label='setosa')
sns.kdeplot(iris.loc[(iris['species']=='virginica'),
'sepal_length'], color='r', shade=True, Label='virginica')
# Setting up the samples
iris_setosa = iris.query("species=='setosa'")
iris_virginica = iris.query("species=='virginica'")
# Plotting the KDE Plot
sns.kdeplot(iris_setosa['sepal_length'],
iris_setosa['sepal_width'],
color='r', shade=True, Label='Iris_Setosa',
cmap="Reds", shade_lowest=False)
# Plotting the KDE Plot
sns.kdeplot(iris_virginica['sepal_length'],
iris_virginica['sepal_width'],
color='r', shade=True, Label='iris_virginica',
cmap="Blues", shade_lowest=False)
Biểu đồ hộp, còn được gọi là biểu đồ hộp và râu ria, được sử dụng để biểu diễn các nhóm dữ liệu số bằng các phần tư. Nó được gọi là sơ đồ hộp và râu vì nó bao gồm một hộp và râu. Boxplot cũng được sử dụng để phát hiện giá trị ngoại lệ trong tập dữ liệu.
Biểu đồ hộp được tạo thành từ một bản tóm tắt của 5 điểm dữ liệu khác nhau: tối thiểu, phần tư thứ nhất, trung vị, phần tư thứ ba và tối đa.
import seaborn as sns
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", data=tips)
Hãy để tôi giải thích ngắn gọn cốt truyện trên.
Biểu đồ violon, cũng giống như biểu đồ hình hộp, tóm tắt dữ liệu số thành một tập hợp các danh mục. Về cơ bản, chúng là một biểu đồ hộp với ước tính mật độ hạt nhân (KDE) được phủ lên cùng với phạm vi hộp và được phản chiếu để làm cho nó trông đẹp mắt. Không giống như biểu đồ hình hộp, trong đó tất cả các thành phần của biểu đồ tương ứng với các điểm dữ liệu thực tế, biểu đồ vĩ cầm trình bày ước tính mật độ hạt nhân của phân phối cơ bản. Dưới đây là một số ví dụ về cốt truyện vĩ cầm:
import seaborn as sns
tips = sns.load_dataset("tips")
ax = sns.violinplot(x=tips["total_bill"])
sns.violinplot(x="day", y="total_bill", hue="smoker",
data=tips, palette="muted")
Bây giờ chúng ta cũng có thể biểu diễn đồ thị trên theo cách này bằng cách đặt tham số split thành True:
sns.violinplot(x="day", y="total_bill", hue="smoker",
data=tips, palette="muted", split=True)
Bản đồ nhiệt là biểu diễn đồ họa hai chiều của dữ liệu trong đó các giá trị riêng lẻ có trong ma trận được biểu thị dưới dạng màu. Trong Seaborn, chúng tôi có thể tạo các bản đồ nhiệt có chú thích có thể được điều chỉnh bằng Matplotlib khi cần.
Bây giờ, nếu chúng tôi lấy dữ liệu 'chuyến bay' từ tập dữ liệu và chuyển đổi dữ liệu đó hàng tháng như minh họa bên dưới, điều này có thể cung cấp cho chúng tôi rất nhiều thông tin về dữ liệu. Nhưng thông tin này ở dạng bảng và có thể được hiển thị tốt hơn bằng cách sử dụng bản đồ nhiệt như hình bên dưới:
flights=sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
print(flights)
Output:
year 1949 1950 1951 1952 1953 ... 1956 1957 1958 1959 1960
month ...
January 112 115 145 171 196 ... 284 315 340 360 417
February 118 126 150 180 196 ... 277 301 318 342 391
March 132 141 178 193 236 ... 317 356 362 406 419
April 129 135 163 181 235 ... 313 348 348 396 461
May 121 125 172 183 229 ... 318 355 363 420 472
June 135 149 178 218 243 ... 374 422 435 472 535
July 148 170 199 230 264 ... 413 465 491 548 622
August 148 170 199 242 272 ... 405 467 505 559 606
September 136 158 184 209 237 ... 355 404 404 463 508
October 119 133 162 191 211 ... 306 347 359 407 461
November 104 114 146 172 180 ... 271 305 310 362 390
December 118 140 166 194 201 ... 306 336 337 405 432
sns.heatmap(flights,linewidths=.5,cmap="YlGnBu")
Bây giờ chúng ta cũng có thể đặt các giá trị tương ứng vào các hộp bằng cách sử dụng tham số chú thích của chức năng này
import seaborn as sns
car_crashes = sns.load_dataset("car_crashes")
corr=car_crashes.corr()
print(corr)
sns.heatmap(corr,annot=True,linewidths=.5,cmap="YlGnBu")
Output
total speeding ... ins_premium ins_losses
total 1.000000 0.611548 ... -0.199702 -0.036011
speeding 0.611548 1.000000 ... -0.077675 -0.065928
alcohol 0.852613 0.669719 ... -0.170612 -0.112547
not_distracted 0.827560 0.588010 ... -0.174856 -0.075970
no_previous 0.956179 0.571976 ... -0.156895 -0.006359
ins_premium -0.199702 -0.077675 ... 1.000000 0.623116
ins_losses -0.036011 -0.065928 ... 0.623116 1.000000
Phương pháp bản đồ cụm vẽ một tập dữ liệu ma trận dưới dạng bản đồ nhiệt được nhóm theo thứ bậc. Nó sử dụng các cụm phân cấp để sắp xếp dữ liệu theo độ tương tự. Thao tác này sắp xếp lại dữ liệu cho các hàng và cột, đồng thời hiển thị nội dung tương tự cạnh nhau để hiểu sâu hơn về dữ liệu.
import seaborn as sns
flights=sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
sns.clustermap(flights,linewidths=.5,cmap="coolwarm")
Như bạn có thể thấy trong bản đồ này, tất cả các cột và hàng có dữ liệu tương tự nhau và bây giờ cả năm và tháng đều không theo thứ tự như chúng ta đã thấy trong bản đồ nhiệt. Chúng tôi có thể sửa đổi nó một chút và chỉ nhóm các hàng hoặc cột, đây là cách thực hiện:
import seaborn as sns
flights=sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
sns.clustermap(flights,linewidths=.5,cmap="coolwarm",col_cluster=False)
Bây giờ tất cả các năm đều theo thứ tự, nhưng các tháng được nhóm lại và do đó không theo thứ tự
Lưới khía cạnh tạo thành một ma trận gồm các bảng được xác định theo hàng và cột, phân chia các biến. Do bảng điều khiển, một biểu đồ trông giống như nhiều biểu đồ. Nó rất hữu ích để phân tích tất cả các kết hợp thành hai biến riêng biệt.
Ưu điểm của việc sử dụng Facet là chúng ta có thể chèn một biến khác vào biểu đồ. Biểu đồ trên được chia thành hai biểu đồ dựa trên biến thứ ba có tên là 'chế độ ăn uống' bằng cách sử dụng tham số 'col'. Chúng ta cũng có thể thêm một tham số “đường” có thể giúp thêm một biến nữa vào biểu đồ của chúng ta. Bây giờ, biểu đồ dưới đây cho thấy mối quan hệ giữa tiền boa và tổng hóa đơn và cũng cho thấy mối quan hệ của nó với hai biến số khác, đó là giới tính và thời gian.
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="time")
g.map(sns.scatterplot, "total_bill", "tip")
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="time", row="sex")
g.map(sns.scatterplot, "total_bill", "tip")
Biểu đồ cặp tạo một lưới trục để mỗi biến số trong dữ liệu được chia sẻ trên các trục y trong một hàng và các trục x trong một cột. Các biểu đồ đường chéo được xử lý khác nhau: một biểu đồ phân phối đơn biến được vẽ để hiển thị phân phối biên của dữ liệu trong mỗi cột.
Đồ thị cặp là một cách thực sự đơn giản để trực quan hóa mối quan hệ giữa mỗi biến. Nó tạo ra một ma trận các mối quan hệ giữa từng biến trong dữ liệu của bạn để xem nhanh dữ liệu của chúng tôi, như bạn sẽ thấy trong ví dụ bên dưới.
import seaborn as sns
from matplotlib import pyplot as plt
df = sns.load_dataset('iris')
sns.set_style("ticks")
sns.pairplot(df,hue = 'species',diag_kind = "kde",kind = "scatter",palette = "husl")
plt.show()
Điều này đưa chúng ta đến phần cuối của bài viết này, nơi chúng ta đề cập đến một số điều cơ bản về Seaborn và tìm hiểu cách vẽ các cốt truyện khác nhau. Bạn có thể nhận khóa học máy học miễn phí từ học viện học tập tuyệt vời, hãy nhấp vào biểu ngữ bên dưới để tìm hiểu thêm.
Nguồn bài viết gốc tại: https://www.mygreatlearning.com
1665988509
Seaborn is a Python data visualization library based on Matplotlib. It is used to draw attractive and informative statistical graphics. To adjust the figure size of the seaborn plot we will use the subplots function of matplotlib.pyplot.
In this article we cover two ways to change the figure size of a seaborn plot in Python.
The first method can be used to change the size of “axes-level” plots such as sns.scatterplot() or sns.boxplot() plots:
sns.set(rc={"figure.figsize":(8, 4)}) #width=8, #height=4
To call set
with the rc
argument set to a dict with the 'figure.figsize'
option to the width and height of the figure in a tuple.
Example:
The following code shows how to create a seaborn scatterplot with a width of 10 and a height of 6:
import pandas as pd
import seaborn as sns
#create data
df = pd.DataFrame({"var1": [25, 12, 15, 14, 19, 23, 25, 29],
"var2": [5, 7, 7, 9, 12, 9, 9, 4],
"var3": [11, 8, 10, 6, 6, 5, 9, 12]})
#define figure size
sns.set(rc={"figure.figsize":(10, 5)}) #width=10, height=5
#display scatterplot
sns.scatterplot(data=df, x="var1", y="var2")
And the following code shows how to create a seaborn boxplot with a width of 6 and a height of 5:
#define figure size
sns.set(rc={"figure.figsize":(6, 5)}) #width=6, height=5
#display scatterplot
sns.boxplot(data=df["var1"])
The second method can be used to change the size of “figure-level” plots such as sns.lmplot() and sns.catplot() or sns.jointplot() plots.
This method requires you to specify the height and aspect (the ratio of the width to the height) within the chart arguments:
sns.lmplot(data=df, x="var1", y="var2",
height=6, aspect=1.5) #height=6, width=1.5 times larger than height
Example:
For figure-level plots (such as sns.lmplot, sns.catplot, sns.jointplot, etc.), you must specify the height and width within the chart itself.
The following code shows how to create a seaborn lmplot with a height of 5 and a width 1.5 times larger than the height:
import pandas as pd
import seaborn as sns
#create data
df = pd.DataFrame({"var1": [25, 12, 15, 14, 19, 23, 25, 29],
"var2": [5, 7, 7, 9, 12, 9, 9, 4],
"var3": [11, 8, 10, 6, 6, 5, 9, 12]})
#create lmplot
sns.lmplot(data=df, x="var1", y="var2",
height=5, aspect=1.5) #height=5, width=1.5 times larger than height
And the following code shows how to create a seaborn jointplot with a height of 3.5. Since a jointplot is square by default, we don’t need to specify the aspect value:
sns.jointplot(data=df, x="var1", y="var2", height=3.5)
1653377258
This Python Seaborn cheat sheet with code samples guides you through the data visualization library that is based on Matplotlib.
You most probably will know by now that data storytelling, accomplished by data visualization, amongst other things, is an essential skill for every data scientist: after you have turned the raw data into understanding, insights and knowledge, you also need to communicate these findings effectively to your audience.
For most beginners, the first Python data visualization library that they use is, naturally, Matplotlib. It is a Python 2D plotting library that enables users to make publication-quality figures. It is quite an extensive library where a cheat sheet will definitely come in handy when you're learning, but when you manage to use this library effectively, you'll also be able to get insights and work better with other packages, such as Pandas, that intend to build more plotting integration with Matplotlib as time goes on.
Another package that you'll be able to tackle easily is Seaborn, the statistical data visualization library of Python.
DataCamp has created a Seaborn cheat sheet for those who are ready to get started with this data visualization library with the help of a handy one-page reference.
You'll see that this cheat sheet presents you with the five basic steps that you can go through to make beautiful statistical graphs in Python.
Check out the infographic by clicking on the button below:
This cheat sheet will walk you through the five steps that you need to go through to make these plots: you'll see how you can load in data, set the figure aesthetics, plot, customize and eventually, show or save your plot with Seaborn.
Have this Cheat Sheet at your fingertips
Original article source at https://www.datacamp.com
#python #seaborn #cheatsheet
1653038040
Let's understand how to analyze data in python using the pandas and seaborn library by going through this mini project where we'll look at the tips dataset of seaborn library. This is a beginner level basic tutorial for beginners. We'll look at this dataset from multiple perspective by exploring the data as well as create visualizations using the in built pandas function as well as some of the advance functions of seaborn library.
After completing the project with exercises give, you'll be comfortable in taking any new dataset and analyze it for data analysis perspective.
1648996020
Seaborn: statistical data visualization
Seaborn is a Python visualization library based on matplotlib. It provides a high-level interface for drawing attractive statistical graphics.
Online documentation is available at seaborn.pydata.org.
The docs include a tutorial, example gallery, API reference, and other useful information.
To build the documentation locally, please refer to doc/README.md
.
There is also a FAQ page, currently hosted on GitHub.
Seaborn supports Python 3.7+ and no longer supports Python 2.
Installation requires numpy, pandas, and matplotlib. Some functions will optionally use scipy and/or statsmodels if they are available.
The latest stable release (and required dependencies) can be installed from PyPI:
pip install seaborn
It is also possible to include optional dependencies (only relevant for v0.12+):
pip install seaborn[all]
Seaborn can also be installed with conda:
conda install seaborn
Note that the main anaconda repository typically lags PyPI in adding new releases, but conda-forge (-c conda-forge
) typically updates quickly.
A paper describing seaborn has been published in the Journal of Open Source Software. The paper provides an introduction to the key features of the library, and it can be used as a citation if seaborn proves integral to a scientific publication.
Testing seaborn requires installing additional packages listed in ci/utils.txt
.
To test the code, run make test
in the source directory. This will exercise both the unit tests and docstring examples (using pytest) and generate a coverage report.
The doctests require a network connection (unless all example datasets are cached), but the unit tests can be run offline with make unittests
.
Code style is enforced with flake8
using the settings in the setup.cfg
file. Run make lint
to check.
Seaborn development takes place on Github: https://github.com/mwaskom/seaborn
Please submit bugs that you encounter to the issue tracker with a reproducible example demonstrating the problem. Questions about usage are more at home on StackOverflow, where there is a seaborn tag.
Author: mwaskom
Source Code: https://github.com/mwaskom/seaborn
License: BSD-3-Clause License
1643499887
1640136554
In this data analytics with Python full course video, you'll learn to analyze and visualize data using Python libraries. Data analytics plays a vital role in every company for making crucial decisions and improving the business. You will see the different applications of Data Analytics and the various types of Data Analytics. You will deep dive into learning Data Analytics using NumPy, Pandas, Matplotlib, Seaborn and Bokeh.
The below topics are covered in this video:
Data analysis is a process of examining, cleaning, modifying, and modeling data with the purpose of identifying useful information and hidden trends. It helps you understand the data better and make useful decisions.
This Data Analyst Master’s Program in collaboration with IBM will make you an expert in data analytics. In this Data Analytics course, you'll learn analytics tools and techniques, how to work with SQL databases, the languages of R and Python, how to create data visualizations, and how to apply statistics and predictive analytics in a business environment.
#dataanalysis #python #numpy #pandas #matplotlib #seaborn #bokeh
1639688820
Python is designed to make it easy for developers to create new projects in the language. The libraries in Python for Data Visualization are powerful and provide an easy way to make an attractive graph in a few lines. It’s easy to get lost in the many data visualization libraries for Python, so here’s a quick rundown of what can be done with these tools.
1637244000
👉Exploratory Data Analysis (EDA) is an approach of analyzing datasets to summarize their main characteristics, often using statistical graphics and other data visualization methods. Various statistical models can be used or not, but primarily EDA is used for seeing what the data can tell us beyond the formal modeling or hypothesis testing task.
⭐️You can see more at the link at the end of the article. Thank you for your interest in the blog, if you find it interesting, please give me a like, comment and share with everyone. Thanks! ❤️
1632308640
Machine learning is a subdivision of Artificial Intelligence and is the process by which computers can learn and make predictions from data without being explicitly programmed to do so. This series of articles will look at taking a dataset from basic well log measurements through to petrophysical property prediction. These articles were originally presented at the SPWLA 2021 Conference during a Machine Learning and AI Workshop. They have since been expanded and updated to form these articles.
1628335620
As you’ve probably guessed, this is where Seaborn comes in. Seaborn isn’t a third-party library, so you can get started without creating user accounts or worrying about API limits, etc. Seaborn is also built on top of Matplotlib, making it the logical next step up for anybody wanting some firepower from their charts. We’ll explore Seaborn by charting some data ourselves.
1628177850
Great Learning brings you this live session on “Python For Machine Learning”. Python is a famous programming language when it comes to Machine Learning. In this session, we will be exploring the important libraries required for implementing machine learning tasks. We will start off with the library called NumPy, which would help us to do numerical computation. We will work with single-dimensional as well as multi-dimensional arrays. Going ahead, we will work with the Pandas library. Pandas library is the core library for data wrangling and data manipulation. In Pandas, we will be working with both Series object as well as Dataframes. Further, we will work with the library called Seaborn, which is the core library for data visualization. Finally, there will be a QnA where you can ask all your doubts and queries. If you're looking to learn and advance in Python for the purpose of Machine Learning, do not forget to join this session!
#python #machinelearning #numpy #pandas #seaborn
1626407280
In this video, I am trying to explain about Introduction to Seaborn library in Seaborn library (in English). Please do watch the complete video for in-depth information.
Link to our [ Hindi ] Youtube Channel: https://bit.ly/2Lyw5f9
WsCubeTech – Digital Marketing Agency & Institute.
✔ We can help you to create a comprehensive Digital Marketing plan to take your business to new heights.
✔ Offering Job Oriented Most Latest, Updated and advanced Digital Marketing Courses with Practical, Hands-on Live Projects Training & Exposure. ( Both in English & Hindi)
For More information : Call us at : +91- 92696-98122 , 8561089567
Or visit at : https://www.wscubetech.com/
Please don’t forget to Like, Share & Subscribe
►Subscribe: http://bit.ly/wscubechannel
► Facebook : https://www.facebook.com/wscubetech.india
► Twitter : https://twitter.com/wscube
► Instagram : https://www.instagram.com/wscubetechindia/
► LinkedIn : https://www.linkedin.com/company/wscube-tech/
► Youtube : https://www.youtube.com/c/wscubetechjodhpur
► Website: http://wscubetech.com
------------------------------------------| Thanks |----------------------------
#Matplotlib #Seabornlibrary #PlotsinSeaborn
#matplotlib #seabornlibrary #seaborn
1626392580
In this video, I am trying to explain about Introduction to Seaborn library in Seaborn library (in English). Please do watch the complete video for in-depth information.
Link to our [ Hindi ] Youtube Channel: https://bit.ly/2Lyw5f9
WsCubeTech – Digital Marketing Agency & Institute.
✔ We can help you to create a comprehensive Digital Marketing plan to take your business to new heights.
✔ Offering Job Oriented Most Latest, Updated and advanced Digital Marketing Courses with Practical, Hands-on Live Projects Training & Exposure. ( Both in English & Hindi)
For More information : Call us at : +91- 92696-98122 , 8561089567
Or visit at : https://www.wscubetech.com/
Please don’t forget to Like, Share & Subscribe
►Subscribe: http://bit.ly/wscubechannel
► Facebook : https://www.facebook.com/wscubetech.india
► Twitter : https://twitter.com/wscube
► Instagram : https://www.instagram.com/wscubetechindia/
► LinkedIn : https://www.linkedin.com/company/wscube-tech/
► Youtube : https://www.youtube.com/c/wscubetechjodhpur
► Website: http://wscubetech.com
------------------------------------------| Thanks |----------------------------
#Matplotlib #Seabornlibrary #PlotsinSeaborn
#matplotlib #seabornlibrary #seaborn
1626377700
In this video, I am trying to explain about Introduction to Seaborn library in Seaborn library (in English). Please do watch the complete video for in-depth information.
Link to our [ Hindi ] Youtube Channel: https://bit.ly/2Lyw5f9
WsCubeTech – Digital Marketing Agency & Institute.
✔ We can help you to create a comprehensive Digital Marketing plan to take your business to new heights.
✔ Offering Job Oriented Most Latest, Updated and advanced Digital Marketing Courses with Practical, Hands-on Live Projects Training & Exposure. ( Both in English & Hindi)
For More information : Call us at : +91- 92696-98122 , 8561089567
Or visit at : https://www.wscubetech.com/
Please don’t forget to Like, Share & Subscribe
►Subscribe: http://bit.ly/wscubechannel
► Facebook : https://www.facebook.com/wscubetech.india
► Twitter : https://twitter.com/wscube
► Instagram : https://www.instagram.com/wscubetechindia/
► LinkedIn : https://www.linkedin.com/company/wscube-tech/
► Youtube : https://www.youtube.com/c/wscubetechjodhpur
► Website: http://wscubetech.com
------------------------------------------| Thanks |----------------------------
#Matplotlib #Seabornlibrary #Seaborn
#matplotlib #seabornlibrary #seaborn