Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if xlim:
df = df.loc[
(df[value_label] >= xlim[0])&
(df[value_label] <= xlim[1])
]
# Define colors
## The colormap is applied inversely, so we go from stop to start.
cm_subsection = np.linspace(stop, start, len(structures))
cmap = plt.get_cmap(cmap)
pal = [ cmap(x) for x in cm_subsection ]
# Initialize the FacetGrid object
aspect = mpl.rcParams['figure.figsize']
ratio = aspect[0]/aspect[1]
g = sns.FacetGrid(df,
row='Structure',
hue='Structure',
aspect=max_rois*ratio,
height=aspect[1]/max_rois,
palette=pal,
xlim=xlim,
ylim=ylim,
despine=True,
)
# Draw the densities in a few steps
lw = mpl.rcParams['lines.linewidth']
g.map(sns.kdeplot, value_label, clip_on=False, gridsize=500, shade=True, alpha=1, lw=lw/4.*3, bw=bw)
g.map(sns.kdeplot, value_label, clip_on=False, gridsize=500, color="w", lw=lw, bw=bw)
g.map(plt.axhline, y=0, lw=lw, clip_on=False)
sns.violinplot("Sex", "Age", hue="Survived", data=train_data, split=True, ax=ax[1])
ax[1].set_title('Sex and Age vs Survived')
ax[1].set_yticks(range(0, 110, 10))
# Age
plt.figure(figsize = (12, 5))
plt.subplot(121)
DataSet['Age'].hist(bins=70)
plt.xlabel('Age')
plt.ylabel('Num')
plt.subplot(122)
DataSet.boxplot(column='Age', showfliers=False)
plt.show()
facet = sns.FacetGrid(DataSet, hue = "Survived", aspect = 4)
facet.map(sns.kdeplot, 'Age', shade = True)
facet.set(xlim = (0, DataSet['Age'].max()))
facet.add_legend()
# average survived passsengers by age
fig, axis1 = plt.subplots(1, 1, figsize = (18, 4))
DataSet["Age_int"] = DataSet["Age"].astype(int)
average_age = DataSet[["Age_int", "Survived"]].groupby(['Age_int'], as_index = False).mean()
sns.barplot(x = 'Age_int', y = 'Survived', data = average_age)
DataSet['Age'].describe()
bins = [0, 12, 18, 65, 100]
DataSet['Age_group'] = pd.cut(DataSet['Age'], bins)
by_age = DataSet.groupby('Age_group')['Survived'].mean()
by_age.plot(kind = 'bar')
# -*- coding: utf-8 -*-
#https://seaborn.pydata.org/tutorial/axis_grids.html
#-----------------------------
#%
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks")
from pydataset import data
mtcars = data('mtcars')
mtcars.head()
mtcars.cyl.value_counts()
#no of cylinders
g = sns.FacetGrid(mtcars, col="cyl")
plt.figure(figsize=(6, 5))
g = sns.FacetGrid(mtcars, col="cyl")
g.map(plt.hist, "mpg");
#
g = sns.FacetGrid(mtcars, col="cyl", hue="gear")
g.map(plt.scatter, "wt", "mpg", alpha=.7)
g.add_legend();
#
#
g = sns.FacetGrid(mtcars, row='vs', col="cyl", hue="gear")
g.map(plt.scatter, "wt", "mpg", alpha=.7)
g.add_legend();
df = df.query("value >= 0.0")
# Map the gas species from ugm3 to ppb (gas-phase species only)
df['corrected'] = df.apply(lambda x: openaq.utils.mass_to_mix(x['value'], x['parameter'], unit='ppb'), axis=1)
# Build a custom plot function to make nice datetime plots
def dateplot(y, **kwargs):
ax = plt.gca()
data = kwargs.pop("data")
rs = kwargs.pop("rs", '12h')
data.resample(rs).mean().plot(y=y, ax=ax, grid=False, **kwargs)
# Set up a FacetGrid
g = sns.FacetGrid(df, col='parameter', col_wrap=3, size=4, hue='parameter', sharey=False)
# Map the dataframe to the grid
g.map_dataframe(dateplot, "corrected", rs='12h')
# Set the titles
g.set_titles("{col_name}", fontsize=16)
# Set the axis labels
g.set_axis_labels("", "value")
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks")
# Create a dataset with many short random walks
rs = np.random.RandomState(4)
pos = rs.randint(-1, 2, (20, 5)).cumsum(axis=1)
pos -= pos[:, 0, np.newaxis]
step = np.tile(range(5), 20)
walk = np.repeat(range(20), 5)
df = pd.DataFrame(np.c_[pos.flat, step, walk],
columns=["position", "step", "walk"])
# Initialize a grid of plots with an Axes for each walk
grid = sns.FacetGrid(df, col="walk", hue="walk", col_wrap=5, size=1.5)
# Draw a horizontal line to show the starting point
grid.map(plt.axhline, y=0, ls=":", c=".5")
# Draw a line plot to show the trajectory of each random walk
grid.map(plt.plot, "step", "position", marker="o", ms=4)
# Adjust the tick positions and labels
grid.set(xticks=np.arange(5), yticks=[-3, 3],
xlim=(-.5, 4.5), ylim=(-3.5, 3.5))
# Adjust the arrangement of the plots
grid.fig.tight_layout(w_pad=1)
"""
Facetting histograms by subsets of data
=======================================
_thumb: .42, .57
"""
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="darkgrid")
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, row="sex", col="time", margin_titles=True)
bins = np.linspace(0, 60, 13)
g.map(plt.hist, "total_bill", color="steelblue", bins=bins)
return 'Child'
elif(age <= 25):
return 'Young'
elif(age <= 50):
return 'Middle'
else:
return 'Old'
titanic_train['Age1'] = titanic_train['Age'].map(convert_age)
sns.factorplot(x="Age1", hue="Survived", data=titanic_train, kind="count", size=6)
sns.FacetGrid(titanic_train, row="Survived",size=8).map(sns.kdeplot, "SibSp").add_legend()
sns.FacetGrid(titanic_train, row="Survived",size=8).map(sns.kdeplot, "Parch").add_legend()
titanic_train['FamilySize'] = titanic_train['SibSp'] + titanic_train['Parch'] + 1
titanic_train['FamilySize'].describe()
sns.FacetGrid(titanic_train, row="Survived",size=8).map(sns.kdeplot, "FamilySize").add_legend()
def convert_familysize(size):
if(size == 1):
return 'Single'
elif(size <=3):
return 'Small'
elif(size <= 6):
return 'Medium'
else:
return 'Large'
titanic_train['FamilySize1'] = titanic_train['FamilySize'].map(convert_familysize)
sns.factorplot(x="FamilySize1", hue="Survived", data=titanic_train, kind="count", size=6)
def mdsplot(df, icons=None, zoom=None):
"""
Plot multidimensional scaling results.
:Args:
df
:Kwargs:
- icons ()
- zoom (int or None, default: None)
"""
sns.set_style('white')
g = sns.FacetGrid(df, col='layer', size=9, #col_wrap=4, size=2,
sharex=False, sharey=False, aspect=1)
g.map(_mdsplot, 'x', 'y', color='white', icons=icons, zoom=zoom)
----------
alphasdf : pandas DataFrame
columns ['study', 'alpha', 'DiseaseState']
col_order : list
dataset IDs in the order they should be plotted
labeldict : dict
dictionary with {dataset: label}
mteric : str
alpha diversity metric, to use in labeling y axis
Returns
-------
fig : Figure
"""
sns.set_style('white')
g = sns.FacetGrid(alphasdf, col='study', col_wrap=6,
col_order=col_order, sharex=False, sharey=False)
g = g.map(sns.boxplot, "DiseaseState", "alpha")
g = g.map(sns.stripplot, "DiseaseState", "alpha", split=True, jitter=True,
size=5, linewidth=0.6)
fig = plt.gcf()
fig.set_size_inches(14.2, 9)
# Fix y-axis gridlines
axs = g.axes
for i in range(len(axs)):
ax = axs[i]
yticks = ax.get_yticks()
# If bottom limit is between 0 and 1 (i.e. not simpson)
if not (yticks[0] < 1 and yticks[0] > 0):
ax.set_ylim(floor(yticks[0]), floor(yticks[-1]))