本文整理匯總了Python中seaborn.pairplot方法的典型用法代碼示例。如果您正苦於以下問題:Python seaborn.pairplot方法的具體用法?Python seaborn.pairplot怎麽用?Python seaborn.pairplot使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類seaborn
的用法示例。
在下文中一共展示了seaborn.pairplot方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: jointplot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def jointplot(self, other, column, **kwargs):
"""
Generate a seaborn jointplot for given column in asset compared to
another asset.
Parameters:
- other: The other asset's dataframe
- column: The column name to use for the comparison.
- kwargs: Keyword arguments to pass down to `sns.pairplot()`
Returns:
A seaborn jointplot
"""
return sns.jointplot(
x=self.data[column],
y=other[column],
**kwargs
)
示例2: pairplot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def pairplot(self, **kwargs):
"""
Generate a seaborn pairplot for this asset group.
Parameters:
- kwargs: Keyword arguments to pass down to `sns.pairplot()`
Returns:
A seaborn pairplot
"""
return sns.pairplot(
self.data.pivot_table(
values='close', index=self.data.index, columns='name'
),
diag_kind='kde',
**kwargs
)
示例3: plotInteractions
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def plotInteractions(data, n_clusters):
'''
Plot the interactions between variables
'''
# cluster the data
cluster = findClusters_kmeans(data, n_clusters)
# append the labels to the dataset for ease of plotting
data['clus'] = cluster.labels_
# prepare the plot
ax = sns.pairplot(selected, hue='clus')
# and save the figure
ax.savefig(
'../../Data/Chapter04/k_means_{0}_clusters.png' \
.format(n_clusters)
)
# the file name of the dataset
開發者ID:drabastomek,項目名稱:practicalDataAnalysisCookbook,代碼行數:23,代碼來源:clustering_kmeans_search_alternative.py
示例4: plot_auxiliary
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def plot_auxiliary(all_vars, filename, table_size=4):
# All variables need to be (batch_size, sequence_length, dimension)
for i, a in enumerate(all_vars):
if a.ndim == 2:
all_vars[i] = np.expand_dims(a, 0)
dim = all_vars[0].shape[-1]
if dim == 2:
f, ax = plt.subplots(table_size, table_size, sharex='col', sharey='row', figsize=[12, 12])
idx = 0
for x in range(table_size):
for y in range(table_size):
for a in all_vars:
# Loop over the batch dimension
ax[x, y].plot(a[idx, :, 0], a[idx, :, 1], linestyle='-', marker='o', markersize=3)
# Plot starting point of the trajectory
ax[x, y].plot(a[idx, 0, 0], a[idx, 0, 1], 'r.', ms=12)
idx += 1
# plt.show()
plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
plt.close()
else:
df_list = []
for i, a in enumerate(all_vars):
df = pd.DataFrame(all_vars[i].reshape(-1, dim))
df['class'] = i
df_list.append(df)
df_all = pd.concat(df_list)
sns_plot = sns.pairplot(df_all, hue="class", vars=range(dim))
sns_plot.savefig(filename)
plt.close()
示例5: make_pairplot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def make_pairplot(self, num_components_to_plot=4, outpath=None, dpi=150):
# Get columns
components_to_plot = [self.principal_observations_df.columns[x] for x in range(num_components_to_plot)]
# Plot
plot = sns.pairplot(data=self.principal_observations_df, hue=self.observation_colname,
vars=components_to_plot, markers=self.markers, size=4)
plt.subplots_adjust(top=.95)
plt.suptitle(self.plot_title)
if outpath:
plot.fig.savefig(outpath, dpi=dpi)
else:
plt.show()
plt.close()
示例6: savePair
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def savePair(df,samplesize=20000):
df1 = df.sample(samplesize)
sns.set(style="ticks")
sns.set_context("paper")
sns.pairplot(df1)
plt.title('Pair Graph')
plt.savefig(pair_path)
#畫滑動平均圖,默認12階
示例7: plot_pairplots
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def plot_pairplots(data, labels, alpha, mis, column_label, topk=5, prefix='', focus=''):
cmap = sns.cubehelix_palette(as_cmap=True, light=.9)
plt.rcParams.update({'font.size': 32})
m, nv = mis.shape
for j in range(m):
inds = np.where(np.logical_and(alpha[j] > 0, mis[j] > 0.))[0]
inds = inds[np.argsort(- alpha[j, inds] * mis[j, inds])][:topk]
if focus in column_label:
ifocus = column_label.index(focus)
if not ifocus in inds:
inds = np.insert(inds, 0, ifocus)
if len(inds) >= 2:
plt.clf()
subdata = data[:, inds]
columns = [column_label[i] for i in inds]
subdata = pd.DataFrame(data=subdata, columns=columns)
try:
sns.pairplot(subdata, kind="reg", diag_kind="kde", height=5, dropna=True)
filename = '{}/pairplots_regress/group_num={}.pdf'.format(prefix, j)
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
plt.suptitle("Latent factor {}".format(j), y=1.01)
plt.savefig(filename, bbox_inches='tight')
plt.clf()
except:
pass
subdata['Latent factor'] = labels[:,j]
try:
sns.pairplot(subdata, kind="scatter", dropna=True, vars=subdata.columns.drop('Latent factor'), hue="Latent factor", diag_kind="kde", height=5)
filename = '{}/pairplots/group_num={}.pdf'.format(prefix, j)
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
plt.suptitle("Latent factor {}".format(j), y=1.01)
plt.savefig(filename, bbox_inches='tight')
plt.close('all')
except:
pass
示例8: plot_correlations
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def plot_correlations(ds, corr, corrcat):
sns.set()
plt.gcf().clear()
if corrcat != '': sns.pairplot(ds[corr], hue = corrcat)
else: sns.pairplot(ds[corr])
from io import BytesIO
figfile = BytesIO()
plt.savefig(figfile, format='png')
figfile.seek(0) # rewind to beginning of file
import base64
figdata_png = base64.b64encode(figfile.getvalue())
return figdata_png
示例9: visualize_hist_pairplot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def visualize_hist_pairplot(X,y,selected_feature1,selected_feature2,features,diag_kind):
"""
Visualize the pairwise relationships (Histograms and Density Funcions) between classes and respective attributes
Keyword arguments:
X -- The feature vectors
y -- The target vector
selected_feature1 - First feature
selected_feature1 - Second feature
diag_kind -- Type of plot in the diagonal (Histogram or Density Function)
"""
#create data
joint_data=np.column_stack((X,y))
column_names=features
#create dataframe
df=pd.DataFrame(data=joint_data,columns=column_names)
#plot
palette = sea.hls_palette()
splot=sea.pairplot(df, hue="Y", palette={0:palette[2],1:palette[0]},vars=[selected_feature1,selected_feature2],diag_kind=diag_kind)
splot.fig.suptitle('Pairwise relationship: '+selected_feature1+" vs "+selected_feature2)
splot.set(xticklabels=[])
# plt.subplots_adjust(right=0.94, top=0.94)
#save fig
output_dir = "img"
save_fig(output_dir,'{}/{}_{}_hist_pairplot.png'.format(output_dir,selected_feature1,selected_feature2))
# plt.show()
示例10: plot_pairplot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def plot_pairplot(csv_filename, fig_filename, top=None):
import seaborn as sns
import pandas as pd
sns.set(style="ticks", color_codes=True)
quants = pd.read_csv(csv_filename)
if top is not None:
quants = quants[:top]
g = sns.pairplot(quants, kind='reg', diag_kind='kde', markers='.')
g.savefig(fig_filename)
示例11: plot_scattermatrix
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def plot_scattermatrix(data, target):
df = pd.DataFrame(data)
df['target'] = target
return sns.pairplot(df, hue='target', diag_kind='hist')
示例12: basicStat
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def basicStat(dataBunch):
sns.set(style='whitegrid',context='notebook')
cols=['lat','lng','price','overall_rating','service_rating','facility_rating','hygiene_rating','image_num','comment_num','favorite_num','checkin_num'] #用於標識frame數據框的列索引
frame=pd.DataFrame(dataBunch.data[:],columns=cols) #轉換為pandas庫的frame數據框格式,方便數據觀察和提取
# print(frame)
sns.pairplot(frame[cols],size=2.5) #兩兩數據的散點圖,用於觀察數據間的關係
plt.show()
cm=np.corrcoef(frame[cols].values.T) #計算兩兩間的相關係數
sns.set(font_scale=1.3)
hm=sns.heatmap(cm,cbar=True,annot=True,square=True,fmt='.2f',annot_kws={'size':13},yticklabels=cols,xticklabels=cols) #熱力圖顯示相關係數,方便直觀查看
plt.show
示例13: ScatterPlot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def ScatterPlot(self):
start = time.time()
sns.set(style="ticks", color_codes=True)
this_dir, this_filename = os.path.split(__file__)
OutFileName = os.path.join(this_dir, 'HTMLTemplate/dist/output/Scatter.png')
fig, ax = plt.subplots()
ax = sns.pairplot(self.df[self.ContinuousFeatures].dropna(),markers="+",palette="husl",kind="reg", plot_kws={'line_kws':{'color':'orange'}})
plt.savefig(OutFileName)
end = time.time()
if self.debug == 'YES':
print('ScatterPlot',end-start)
return OutFileName
示例14: run
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def run(self, params={}):
# Set styles
sns.set_palette(params.get('color_palette'))
sns.set(style=params.get('margin_style'))
# Process the data and create the plot
try:
decoded_data = base64.b64decode(params.get('csv_data'))
except Exception as e:
error = f"Failed to decode base64 encoded CSV data with error: {e}"
self.logger.error(error)
raise e
df = pd.read_csv(BytesIO(decoded_data))
kind = params.get('kind')
hue = params.get('hue')
args = {
"kind": kind
}
if hue and (len(hue) > 0):
args['hue'] = hue
if hue not in df:
error = f"Column for hue ({hue}) not in data set, cannot create plot..."
self.logger.error(error)
return Exception(error)
# Pairgrids have the savefig method, call it directly
self.logger.info("Creating plot...")
plot = sns.pairplot(df, **args)
# bbox_inches is required to ensure that labels are cut off
plot.savefig('plot.png', bbox_inches="tight")
with open('plot.png', 'rb') as f:
plot = base64.b64encode(f.read())
return {
"csv": params.get('csv_data'),
"plot": plot.decode('utf-8')
}
示例15: datahtml
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import pairplot [as 別名]
def datahtml(
bucket_name,
commit_sha,
train_file_path
):
import json
import seaborn as sns
import matplotlib.pyplot as plt
import os
image_path = os.path.join(bucket_name, commit_sha, 'visualization.png')
image_url = os.path.join('https://storage.googleapis.com', bucket_name.lstrip('gs://'), commit_sha, 'visualization.png')
html_path = os.path.join(bucket_name, 'kaggle.html')
# ouptut visualization to a file
import pandas as pd
df_train = pd.read_csv(train_file_path)
sns.set()
cols = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt']
sns.pairplot(df_train[cols], size = 3)
plt.savefig('visualization.png')
from tensorflow.python.lib.io import file_io
file_io.copy('visualization.png', image_path)
rendered_template = """
<html>
<head>
<title>correlation image</title>
</head>
<body>
<img src={}>
</body>
</html>""".format(image_url)
file_io.write_string_to_file(html_path, rendered_template)
metadata = {
'outputs' : [{
'type': 'web-app',
'storage': 'gcs',
'source': html_path,
}]
}
with file_io.FileIO('/mlpipeline-ui-metadata.json', 'w') as f:
json.dump(metadata, f)