【问题标题】:Understanding plt.norm and plt.cbar using Practical example使用实际示例了解 plt.norm 和 plt.cbar
【发布时间】:2020-05-22 22:29:24
【问题描述】:

我正在学习制作彩条,从而学习如何使用 plt.Normalize ,我成功地使它与 scipy.stats.norm 一起工作,但是当我尝试使用 plt.norm 时,我发现我必须做两件事才能使其正常工作:

  • 将 vmin 和 vmax 分别定义为 -1.96 和 1.96,我猜这是因为它们是 95% 置信区间的 z 值,但我仍然不知道为什么我们必须将 vmin 和 vmax 设置为那些价值观
  • 标准差除以 sqrt(元素数)

我不明白为什么这两点对于使用规范很重要。欢迎任何帮助!提前谢谢你

# Use the following data for this assignment:
%matplotlib notebook
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st

df = pd.DataFrame([np.random.normal(33500,150000,3650), 
                   np.random.normal(41000,90000,3650), 
                   np.random.normal(41000,120000,3650), 
                   np.random.normal(48000,55000,3650)], 
                  index=[1992,1993,1994,1995])

new_df = pd.DataFrame()
new_df['mean'] = df.mean(axis =1)
new_df['std'] = df.std(axis =1)
new_df['se'] = df.sem(axis= 1)
new_df['C_low'] = new_df['mean'] - 1.96 * new_df['se']
new_df['C_high'] = new_df['mean'] + 1.96 * new_df['se']

from scipy.stats import norm
import numpy as np
# First, Define a figure
fig = plt.figure()
# next define its the axis and create a plot 
ax = fig.add_subplot(1,1,1)
# change the ticks
xticks = np.array(new_df.index,dtype= 'str')
# remove the top and right borders
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# draw the bars in the axis
bars = ax.bar(xticks,new_df['mean'].values,
             yerr = (1.96*new_df['se'],1.96*new_df['se']),
             capsize= 10)
# define labels
plt.xlabel('YEARS',size = 14)
plt.ylabel('FREQUENCY',size = 14)
# Define color map
cmap = plt.cm.get_cmap('coolwarm')
# define scalar mappable 
sm = plt.cm.ScalarMappable(cmap = cmap)
# draw the color bar
cbar = plt.colorbar(cmap = cmap, mappable =sm)
# define norm (will be used later to turn y to a value from 0 to 1 )

# define the events
class Cursor(object):
    def __init__(self,ax):
        self.ax = ax
        self.lx = ax.axhline(color = 'c')
        self.txt = ax.text(1,50000,'')
    def mouse_movemnt(self,event):
        #behaviour outside of the plot
        if not event.inaxes:
            return
        #behavior inside the plot
        y = event.ydata
        self.lx.set_ydata(y)

        for idx,bar in zip(new_df.index, bars):
            norm = plt.Normalize(vmin =-1.96,vmax = 1.96)
            mean = new_df.loc[idx,'mean']
            err = new_df.loc[idx, 'se']
            std = new_df.loc[idx,'std']/ np.sqrt(df.shape[1]) # not sure why we re dividing by np.sqrt(df.shape[1])
            self.txt.set_text(f'Y = {round(y,2)} \n')
            color_prob = norm( (mean - y)/std)
            #color_prob = norm.cdf(y,loc = mean, scale = err) # you can also use this 
            bar.set_color(  cmap(color_prob))



# connect the events to the plot
cursor = Cursor(ax)
plt.connect('motion_notify_event', cursor.mouse_movemnt)
None

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    经过几个小时的思考,一个解释闯入我的脑海,我能够回答我所有的问题,

    先回答第一点,我先回答第二点,标准差除以sqrt(nbr of element),因为得到的值就是标准差。

    我现在将继续回答第一部分: (我现在不能嵌入图像,也不能使用乳胶,所以我必须放置图像的链接)。但是这里提前得出结论,对于该置信区间内的所有值,函数 (y-mean)/se 会吐出 [−1.96,1.96] 范围内的值

    answer of first part

    如果我遗漏了什么或者你有更好的答案,请与我分享。

    【讨论】:

      猜你喜欢
      • 2018-04-18
      • 2011-11-05
      • 1970-01-01
      • 2010-12-15
      • 2011-06-06
      • 2010-10-06
      • 2014-05-27
      • 1970-01-01
      相关资源
      最近更新 更多