Ternary Countour Plot - Plotly - plotly-python

I have created the above ternary plot using the code below:
import plotly.figure_factory as ff
fig = ff.create_ternary_contour(np.stack((prob0,prob1,prob2)),some_calc_val,
pole_labels=[r'$\text{AxesA}$', r'$\text{AxesB}$', r'$\text{AxesC}$'],
interp_mode='cartesian',
ncontours=50,
colorscale='Jet',
showscale=True,
title=r'$\text{Plot}$')
fig.update_ternaries(
aaxis = dict(
tickmode = 'array',
ticklen = 10,
tickvals = [0.2, 0.4, 0.6, 0.8],
ticktext = [r'$0.2$', r'$0.4$', r'$0.6$', r'$0.8$']
),
baxis = dict(
tickmode = 'array',
ticklen = 10,
tickvals = [0.2, 0.4, 0.6, 0.8],
ticktext = [r'$0.2$', r'$0.4$', r'$0.6$', r'$0.8$']
),
caxis = dict(
tickmode = 'array',
ticklen = 10,
tickvals = [0.2, 0.4, 0.6, 0.8],
ticktext = [r'$0.2$', r'$0.4$', r'$0.6$', r'$0.8$']
)
)
fig.update_layout(width=600, height=600)
fig.show()
Data for refrence
prob0=[9.99960940e-01 6.03061907e-04 9.10372544e-12 9.99952169e-01
2.81419593e-04 2.17084140e-18 9.99882767e-01 5.63535132e-11
1.86320179e-25]
prob1=[3.90598546e-05 9.99396859e-01 6.40065936e-01 4.78313969e-05
5.71105924e-01 1.86904565e-07 5.85691843e-05 1.40045638e-07
1.96443635e-14]
prob2=[4.32181700e-19 7.88323607e-08 3.59934064e-01 5.03536073e-12
4.28612656e-01 9.99999813e-01 5.86636024e-05 9.99999860e-01
1.00000000e+00]
some_calc_val=[3.90598546e-05 6.03140740e-04 3.59934064e-01 4.78314019e-05
4.28894076e-01 1.86904565e-07 1.17232787e-04 1.40101991e-07
1.95399252e-14]
Questions:
I would like to Latexify the ticks for the color bar on the right, I have looked around in the layout but did not find any such color bar which I could update the ticks for
Is it possible to add a little space between the ternary plot and the color bar, the name of the AxesC falls right under the color bar which is not ideal for my use case.
Also is there a way to add labels similar to what is used in go.Countour() which has a showlabels key
Let me know if separate questions need to be posted for each of the above.
References before posting:
https://community.plotly.com/t/how-to-get-the-axis-ticks-of-a-scatter-plot-to-be-shown-in-latex-using-python-python-latex-representation/61302
https://community.plotly.com/t/format-ticks-add-km-at-the-end/60932

Related

Prophet cross_validation method stops unexepectedly #2319

We are currently facing a problem with a Prophet model which stops unexpectedly. We've used optuna as our HyperParameter model searching framework, and gave 400 trials per each TimeSeries (we are traininig Prophet on ~ 1000 Timeseries, 1 by 1, not all at once). For cross validation, we've used the methode from the Prophet class called cross_validation.
Here is the code we've used:
def get_best_hp_prophet_cv(df_for_cv, weeks_to_forecast):
logging.getLogger('prophet').setLevel(logging.ERROR)
logging.getLogger('fbprophet').setLevel(logging.ERROR)
# print('DF entered for search: ', df_for_cv)
cutoffs = generate_cutoffs(df_for_cv, weeks_to_forecast)
def objective(trial):
# print(cutoffs)
# print(df.tail(30))
param_grid = {
"changepoint_prior_scale": trial.suggest_categorical(
"changepoint_prior_scale", [0.001, 0.01, 0.1, 0.5, 0.05, 0.8, 0.9]
),
"seasonality_prior_scale": trial.suggest_categorical(
"seasonality_prior_scale", [0.01, 0.05, 0.1, 0.5, 1.0, 10]
),
"seasonality_mode": trial.suggest_categorical(
"seasonality_mode", ["multiplicative", "additive"]
),
"growth": trial.suggest_categorical("growth", ["linear"]),
"yearly_seasonality": trial.suggest_categorical(
"yearly_seasonality", [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16]
),
"daily_seasonality": trial.suggest_categorical("daily_seasonality",[False]),
"weekly_seasonality": trial.suggest_categorical("weekly_seasonality",[False]),
"uncertainty_samples": trial.suggest_categorical("uncertainty_samples",[0]),
}
prior_scale_month = trial.suggest_categorical('prior_scale_month', [0.001, 0.01, 0.1, 0.5, 0.05, 0.9])
prior_scale_week_num = trial.suggest_categorical('prior_scale_week_num', [0.001, 0.01, 0.1, 0.5, 0.05, 0.9])
prior_scale_avg_month_qty_over_df = trial.suggest_categorical('prior_scale_avg_month_qty_over_df', [0.001, 0.01, 0.1, 0.5, 0.05, 0.9])
prior_scale_avg_week_nr_qty_over_df = trial.suggest_categorical('prior_scale_avg_week_nr_qty_over_df', [0.001, 0.01, 0.1, 0.5, 0.05, 0.9])
# I ve used this only for testing to see if everything works fine
# param_grid = {
# 'changepoint_prior_scale': trial.suggest_categorical('changepoint_prior_scale', [0.001]),
# 'seasonality_prior_scale': trial.suggest_categorical('seasonality_prior_scale',[0.01, 0.1]),
# 'seasonality_mode' : trial.suggest_categorical('seasonality_mode',['additive']),
# 'growth': trial.suggest_categorical('growth',['linear']),
# 'yearly_seasonality': trial.suggest_categorical('yearly_seasonality',[14,15]),
# 'holidays_prior_scale' : trial.suggest_categorical('holidays_prior_scale',[10])
# }
# all_params = [dict(zip(param_grid.keys(), v)) for v in itertools.product(*param_grid.values())]
# mses = [] # Store the MSEs for each params here
# Use cross validation to evaluate all parameters
# for params in all_params:
m = Prophet(**param_grid)
m.add_regressor('month', prior_scale = prior_scale_month)
m.add_regressor('week_num', prior_scale = prior_scale_week_num)
m.add_regressor('avg_month_qty_over_df', prior_scale = prior_scale_avg_month_qty_over_df)
m.add_regressor('avg_week_nr_qty_over_df', prior_scale = prior_scale_avg_week_nr_qty_over_df)
m.fit(df_for_cv)
df_cv = cross_validation(
m, cutoffs=cutoffs, horizon="{} days".format(weeks_to_forecast*7), parallel="processes"
)
df_p = performance_metrics(df_cv, rolling_window=1)
return df_p["mse"].values[0]
# Find the best parameters
optuna_prophet = optuna.create_study(
direction="minimize", sampler=TPESampler(seed=321)
)
# * n_trials optuna hyperparameter.
#optuna_prophet.optimize(objective, n_trials=400)
optuna_prophet.optimize(objective, n_trials=1)
prophet_trial = optuna_prophet.best_trial
prophet_trial_params = prophet_trial.params
list_of_variables_outside_the_param_grid = ['prior_scale_month','prior_scale_week_num','prior_scale_avg_month_qty_over_df','prior_scale_avg_week_nr_qty_over_df']
params_outside_the_param_grid={}
param_grid = {}
for param_name in prophet_trial_params.keys():
if param_name in list_of_variables_outside_the_param_grid:
params_outside_the_param_grid.update({param_name : prophet_trial_params[param_name]})
else:
param_grid.update({param_name : prophet_trial_params[param_name]})
return param_grid, params_outside_the_param_grid
We've used Prophet before, but on less Timeseries (around 20) and with even more nr_of_trials in Optuna and never faced this issue before. Does anybody knows why is this happening? Has anybody a workaround? It always stops at the begging of the 54 trial from Optuna Search.
We've tried to run with only 1 trial on all 1000 Timeseries and it worked end - 2 - end, but still we can't figure it out why it stops on the 54th trial ?
Versions:
Optuna ---- 3.0.3.
Prophet ---- 1.1

How can i remove the connection line between errorbar in matplotlib?

I want to remove the connection line between errorbars...
But i don't know how to remove this connection lines.
from matplotlib import pyplot as plt
#Bar Plot
topics = ['Face Upright', 'Face Inverted']
SOA150 = [70.639, 60.063]
SOA1000 = [-3.076, 11.277]
SOA150err = [22.89, 19.75]
SOA1000err =[30.33, 11.27]
def create_x(t,w,n,d):
return [t*x + w*n for x in range(d)]
value_a_x = create_x(2, 0.8, 1, 2)
value_b_x = create_x(2, 0.8, 2, 2)
ax = plt.subplot()
ax.bar(value_a_x, SOA150, color ='darkorange', capsize = 5)
ax.bar(value_b_x, SOA1000, color = 'darkolivegreen', capsize = 5)
ax.errorbar(value_a_x, SOA150,yerr = SOA150err, capsize=3, color = 'gray', lw=1 )
ax.errorbar(value_b_x, SOA1000,yerr = SOA1000err, capsize=3, color = 'gray', lw=1 )
middle_x = [(a+b)/2 for (a,b) in zip(value_a_x, value_b_x)]
ax.set_xticks(middle_x)
ax.set_xticklabels(topics)
plt.ylim(-40,100)
plt.xlabel('Orientation of Face')
plt.ylabel('Gaze Cueing (ms)')
plt.legend(['150ms SOA', '1000ms SOA'])
ax = plt.axes()
ax.yaxis.grid(lw=0.5)
my graph

How to remove the overlapping in threshold_scale of Choropleth Map?

#ChoroplethMap
bins = list(state_avg_value["price"].quantile([0, 0.25, 0.5, 0.75, 1]))
#state_avg_value_max= state_avg_value['price'].max()
m = folium.Map(location=[48, -102], zoom_start=3)
folium.Choropleth(
geo_data=state_geo,
data=state_avg_value,
columns=["state", "price"],
key_on="feature.properties.name",
fill_color="BuPu",
fill_opacity=0.7,
line_opacity=0.5,
legend_name="Price (in dollars)",
bins=bins,
reset=True,
).add_to(m)
m
#Q. How to remove the overlapping in threshold_scale?
#[ChoroplethMap][1]
#[1]: https://i.stack.imgur.com/Xi4A6.jpg

Is there any other way to find percentage and plot a group bar-chart without using matplotlib?

emp_attrited = pd.DataFrame(df[df['Attrition'] == 'Yes'])
emp_not_attrited = pd.DataFrame(df[df['Attrition'] == 'No'])
print(emp_attrited.shape)
print(emp_not_attrited.shape)
att_dep = emp_attrited['Department'].value_counts()
percentage_att_dep = (att_dep/237)*100
print("Attrited")
print(percentage_att_dep)
not_att_dep = emp_not_attrited['Department'].value_counts()
percentage_not_att_dep = (not_att_dep/1233)*100
print("\nNot Attrited")
print(percentage_not_att_dep)
fig = plt.figure(figsize=(20,10))
ax1 = fig.add_subplot(221)
index = np.arange(att_dep.count())
bar_width = 0.15
rect1 = ax1.bar(index, percentage_att_dep, bar_width, color = 'black', label = 'Attrited')
rect2 = ax1.bar(index + bar_width, percentage_not_att_dep, bar_width, color = 'green', label = 'Not Attrited')
ax1.set_ylabel('Percenatage')
ax1.set_title('Comparison')
xTickMarks = att_dep.index.values.tolist()
ax1.set_xticks(index + bar_width)
xTickNames = ax1.set_xticklabels(xTickMarks)
plt.legend()
plt.tight_layout()
plt.show()
The first block represents how the dataset is split into 2 based upon Attrition
The second block represents the calculation of percentage of Employees in each Department who are attrited and not attrited.
The third block is to plot the given as a grouped chart.
You can do:
(df.groupby(['Department'])
['Attrited'].value_counts(normalize=True)
.unstack('Attrited')
.plot.bar()
)

How to increase the size of the text inside the red circle of the cor plot?

How to increase the size of the text inside the red circle of the cor plot?
Used code:
par(mar=c(1,1,1,1))
pairs.panels(data,
method = "pearson",
hist.col = "#00AFBB",
density = TRUE,
ellipses = TRUE,
pch = 21,
cex = 1.5,
cex.axis = 1.8,
lwd = 2,
rug = TRUE,
stars = TRUE
)
Finally, I got the answer and i.e. to add the argument cex.labels = 2.5,
the final code is
library(psych)
par(mar=c(1,1,1,1))
pairs.panels(data,
method = "pearson",
hist.col = "#00AFBB",
density = TRUE,
ellipses = TRUE,
pch = 21,
cex = 1.5,
cex.axis = 1.8,
cex.labels = 2.5,
lwd = 2,
rug = TRUE,
stars = TRUE
)