I needed to create a bar plot that show:
the mean from some series;
them 95% confidence interval; and,
bars might be colored blue if they are definitely above this value (given the confidence interval), red if they are definitely below this value, or white if they contain this value.
Well, I coded the following lines, but considering I am learning Python, I am always thinking: is this a pythonic way?
You can see this code on here.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from matplotlib.cm import ScalarMappable
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(32000,200000,3650),
np.random.normal(43000,100000,3650),
np.random.normal(43500,140000,3650),
np.random.normal(48000,70000,3650)],
index=[1992,1993,1994,1995])
# Y select by user
y_user = 40000
# Creating the plot
fig, ax = plt.subplots()
# Calculating the probabilities
# I definitely believe this could be more readable
colorlist = [norm.sf(40000, loc=df[df.index == year].mean(axis = 1), scale=df[df.index == year].sem(axis = 1)).item(0) for year in df.index]
# Selecting the pallete
my_cmap = plt.cm.get_cmap('RdBu')
colors = my_cmap(colorlist)
# Creating the bars
ax.bar(df.index, df.mean(axis = 1), yerr=df.sem(axis = 1) * norm.ppf(0.975), color=colors, capsize=10)
# Ploting the y choose by user
plt.axhline(y = y_user, color = 'r', linestyle = '--')
# Controling the xticks
plt.xticks(df.index)
# Creating the colorbar
sm = ScalarMappable(cmap=my_cmap)
sm.set_array([])
cbar = plt.colorbar(sm)
cbar.set_label('Probability to contain the value choose ({})'.format(y_user), rotation=270, labelpad=25)
cbar.set_ticks(np.arange(0, 1.1 , 0.1))
fig.savefig("GregOliveira_Week3.png")
plt.show()
help(np.random.seed)
says The best practice is to not reseed a BitGenerator and gives an example which demonstrates best practice… \$\endgroup\$colorlist
, should that literal40000
not be replaced withy_user
? \$\endgroup\$y_user
claims to be selected by the user but it is hard-coded. Why? \$\endgroup\$