Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
plt.ylim(-0.5, 0.5)
plt.xlim(-3, 3)
plt.xticks([-2, 0, 2],
['Oppose',
'No Opinion',
'Support'],
rotation=90)
plt.yticks([-0.5, 0, 0.5])
plt.tight_layout()
plt.savefig('{0}{1:03.0f}_{2}.png'.format(output_dir, i, column), dpi=200)
plt.close()
## Create title page/chart to break up the loop, saving image
sns.set_style('white', {'xtick.color': 'white', 'axes.labelcolor': 'white'})
plt.figure()
violin = sns.violinplot(x=df['1996'], inner=None, palette='Set2', bw=0.4)
plt.text(0, -1.5,
'Support/oppose law to get a\npolice permit before buying a gun?\n1972-2016',
fontdict=font_h1)
plt.text(-3, -2.35,
'© Aaron Penne\nSource: General Social Survey',
fontdict=font_h2)
plt.title(' ')
plt.ylim(-2, -1)
plt.xlim(-3, 3)
plt.xticks([-2, 0, 2],
['Oppose',
'No Opinion',
'Support'],
rotation=90)
plt.yticks([-2, -0.5, -1])
violin.xaxis.label.set_color('white')
def plot(data, total, title, width=800.0, unit='', dosort=True,
target=None, target2=None):
"""A HTML bar plot given a dictionary and max value."""
if len(data) > 30 and target is not None:
df = pandas.DataFrame(index=data)
if len(title) > 50:
title = title[:50] + '...'
df[title] = pandas.Series(data, index=df.index)
df[target.name] = target.loc[df.index]
if target2 is not None:
df[target2.name] = target2.loc[df.index]
if iscategorical(target):
df.sort_values(by=target.name, inplace=True)
if target2 is None:
# seaborn.barplot(target.name, title, data=df)
seaborn.violinplot(x=target.name, y=title, data=df,
split=True, inner="stick", palette='Set1')
else:
seaborn.barplot(target.name, title, data=df, hue=target2.name,
palette='Set1')
fig = plt.gcf()
fig.autofmt_xdate()
else: # treat X-axis as continuous
if target2 is None:
seaborn.jointplot(target.name, title, data=df, kind='reg')
else:
seaborn.lmplot(target.name, title, data=df,
hue=target2.name, palette='Set1')
# Convert to D3, SVG, javascript etc.
# import mpld3
# result = mpld3.fig_to_html(plt.gcf(), template_type='general',
# use_http=True)
'horizontalalignment': 'left'}
font_title = {'family': 'monospace',
'color': '#6f6f6f',
'weight': 'regular',
'size': 'xx-small',
'va': 'center',
'ha': 'center'}
dpi = 200
figsize = (700/dpi,400/dpi)
pad = 0
## Create all interpolated data charts, saving images
for i, column in enumerate(df):
fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
violin = sns.violinplot(x=df.iloc[:,i],
inner=None,
color='#3f3f3f',
linewidth=0,
bw=0.4,
scale='count',
scale_hue=False)
plt.title(' ')
plt.xlabel('')
plt.ylabel('% of States',
fontname='monospace')
plt.ylim(-0.5, 0.5)
plt.xlim(-2, 5)
plt.xticks([0, 1, 2, 3],
['Constitutional Ban',
'Statutory Ban',
'No Law',
sns.swarmplot(x='hp', y='cyl', data=auto, hue='origin',orient='h')
# Display the plot
plt.show()
#-------------------------------------------------------------------------------------------#
#Constructing violin plots
# Generate a violin plot of 'hp' grouped horizontally by 'cyl'
plt.subplot(2,1,1)
sns.violinplot(x='cyl', y='hp', data=auto)
# Generate the same violin plot again with a color of 'lightgray' and without inner annotations
plt.subplot(2,1,2)
sns.violinplot(x='cyl', y='hp', data=auto, inner=None, color='lightgray')
# Overlay a strip plot on the violin plot
sns.stripplot(x='cyl', y='hp', data=auto, jitter=True, size=1.5)
# Display the plot
plt.show()
#-------------------------------------------------------------------------------------------#
#Plotting joint distributions (1)
# Generate a joint plot of 'hp' and 'mpg'
sns.jointplot('hp', 'mpg', data=auto)
# Display the plot
plt.show()
tbl[tree.num_samples(node)-1] = tbl[
tree.num_samples(node)-1] + tree.branch_length(node)
tot_bl = tot_bl + tree.branch_length(node)
for xi in range(sample_size - 1):
rescaled_x = tbl[xi]/tot_bl
data["total_branch_length"].append(rescaled_x)
tbl_sum[xi] = tbl_sum[xi] + rescaled_x
data["num_leaves"].extend(range(1, sample_size))
basedir = os.path.join("tmp__NOBACKUP__", "xi_dirac_expected_sfs")
if not os.path.exists(basedir):
os.mkdir(basedir)
f = os.path.join(basedir, "n={}_psi={}.png".format(sample_size, psi))
ax = sns.violinplot(
data=data, x="num_leaves", y="total_branch_length", color="grey")
ax.set_xlabel("num leaves")
l1 = ax.plot(np.arange(sample_size - 1), sfs[::], "--", linewidth=3)
l2 = ax.plot(
np.arange(sample_size - 1), [x/num_replicates for x in tbl_sum],
"--", linewidth=3)
ax.legend((l1[0], l2[0]), ("Expected", "Observed"))
pyplot.savefig(f, dpi=72)
pyplot.close('all')
if (not numpy.isnan(new_LLOQ)) & (not numpy.isnan(new_ULOQ)):
if splitByBatch:
p_rect = ax.add_patch(mpatches.Rectangle((-0.5, new_LLOQ), max(batches), (new_ULOQ - new_LLOQ), facecolor='grey', alpha=0.15)) #Rectangle((x,y), width, height)
else:
p_rect = ax.add_patch(mpatches.Rectangle((0, new_LLOQ), 1, (new_ULOQ - new_LLOQ), facecolor='grey', alpha=0.15))
p_rect.set_zorder(0)
# Violin plot
# (remove inf values, only keep plotted SampleTypes)
violin_x = tData.sampleMetadata['Batch'][(SSmask | SPmask | ERmask) & noInfMask].values
violin_y = concentrationValues[(SSmask | SPmask | ERmask) & noInfMask]
violin_subgroup = tData.sampleMetadata['SampleType'][(SSmask | SPmask | ERmask) & noInfMask].values
# make sure we have values to plot
if len(violin_y) > 0:
if splitByBatch:
p_violin = sns.violinplot(x=violin_x, y=violin_y, hue=violin_subgroup, palette=sTypeColourDict, hue_order=hue_order, ax=ax, scale='width', bw=.2, cut=0)
else:
# if not splitting by batch, the x-axis is the SampleType which is already recorder in _subgroup. Order is the same as hue_order. No hue used here
p_violin = sns.violinplot(x=violin_subgroup, y=violin_y, palette=sTypeColourDict, order=hue_order, ax=ax, scale='width', bw=.2, cut=0)
# merged LLOQ / ULOQ lines
if not numpy.isnan(new_LLOQ):
p_LLOQ_line = ax.axhline(y=new_LLOQ, xmin=0, xmax=1, linestyle='-.', color='grey')
if not numpy.isnan(new_ULOQ):
p_ULOQ_line = ax.axhline(y=new_ULOQ, xmin=0, xmax=1, linestyle='-.', color='grey')
# Keep the xlims before batch plots
xlims = ax.get_xlim()
# if plotBatch: batch LOQ lines, already + future out of LOQ samples marked as points
# if False: only already out of LOQ samples points
pt_LOQ_x = []
ylim_percentiles[1]) * DECIMAL_TO_BPS)
else:
ymin = None
ymax = None
if ax is None:
f, ax = plt.subplots(1, 1, figsize=(18, 6))
unstacked_dr = (return_by_q
.multiply(DECIMAL_TO_BPS))
unstacked_dr.columns = unstacked_dr.columns.set_names('forward_periods')
unstacked_dr = unstacked_dr.stack()
unstacked_dr.name = 'return'
unstacked_dr = unstacked_dr.reset_index()
sns.violinplot(data=unstacked_dr,
x='factor_quantile',
hue='forward_periods',
y='return',
orient='v',
cut=0,
inner='quartile',
ax=ax)
ax.set(xlabel='', ylabel='Return (bps)',
title="Period Wise Return By Factor Quantile",
ylim=(ymin, ymax))
ax.axhline(0.0, linestyle='-', color='black', lw=0.7, alpha=0.6)
return ax
def violinplot(ax):
n = 40
p = 8
rs = np.random.RandomState(8)
d = rs.normal(0, 1, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10
sns.violinplot(d, inner="points", ax=ax)
ax.set_title("violinplot()")
else:
attrs = set([getattr(s, by_attribute) for s in samples])
fig, axis = plt.subplots(len(attrs), 1, figsize=(8, len(attrs) * 6))
for i, attr in enumerate(attrs):
_LOGGER.info(attr)
cov = pd.melt(
np.log2(
1
+ self.matrix_raw[
[s.name for s in samples if getattr(s, by_attribute) == attr]
]
),
var_name="Sample name",
value_name="Raw counts (log2)",
)
sns.violinplot(
"Raw counts (log2)",
"Sample name",
orient="horizontal",
palette="tab20",
data=cov,
ax=axis[i],
)
axis[i].set_title(attr)
axis[i].set_xticklabels(axis[i].get_xticklabels(), rotation=90)
sns.despine(fig)
savefig(
fig,
os.path.join(
self.results_dir,
self.name + ".raw_counts.violinplot.by_{}.svg".format(by_attribute),
),
print(df.describe())
#Hypothesis testing
#perform one sample t-test using 1500 as the true mean
print(ss.ttest_1samp(a=df.ix[:,'Abra'],popmean=1500))
#Visulization
matplotlib.rcdefaults()
plt.show(df.plot(kind = 'box'))
pd.options.display.mpl_style = 'default' # Sets the plotting display theme to ggplot2
df.plot(kind = 'box')
sns.boxplot(data=df,width=0.5)
sns.violinplot(df,width=3.5)
plt.show(sns.distplot(df.ix[:,2], rug = True, bins = 15))
with sns.axes_style("white"):
plt.show(sns.jointplot(df.ix[:,1],df.ix[:,2], kind = "kde"))
plt.show(sns.lmplot("Benguet","Ifugao",df))
#Creating custom function
def add_2int(x,y):
return x+y
print(add_2int(2,2))
# an algorithm example
def case(n=10,mu=3,sigma=np.sqrt(5),p=0.025,rep=100):
m=np.zeros((rep,4))