PYTHON:依赖于范围的注释框消失

2024-03-29 15:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,绘制一些数据和拟合的信息框。玩具的例子如下。你知道吗

import numpy as np
import matplotlib.pyplot as plt

#Works
sigma = 0.12
mu = 0.5

#Half Works
sigma = 0.1
mu = 0.3

##None Works
#sigma = 0.05
#mu = 0.2

Sample = np.random.normal(mu, sigma, 10000)

figHS = plt.figure() 
axHS = figHS.add_subplot(1, 1, 1)
n, histbins, patches = axHS.hist(Sample,100, histtype='step', normed=1) 
axHS.annotate("$\mu=%.3f$ \n $\sigma=%.3f$ \n $N=%i$"%
              (Sample.mean(), Sample.std(), len(Sample)),
              xytext=(0.8, 0.85), bbox=dict(boxstyle="sawtooth", fc="w"),
              xy=(0.8, 0.85), textcoords='axes fraction')
axHS.plot(histbins, plt.mlab.normpdf(histbins, mu, sigma))
axHS.annotate(" $\mu=%.3f$ \n $\sigma=%.3f$ \n $N=%s$"%(mu,sigma,"--"),
              xytext=(0.6, 0.85), bbox=dict(boxstyle="round", fc="w"),
              xy=(0.6, 0.85), textcoords='axes fraction')
plt.show()

如果您尝试使用三个不同的输入值,您可以看到它与x范围有关。它可能在1以下以不同方式处理,或者从错误的对象获取范围。因为这是一个玩具的例子,我在我的实际用例中受到更多的限制,所以请不要建议我以完全不同的方式来做,除非像“histbins”这样的值以类似的方式传递。你知道吗

从第一个输入值得到期望的结果。 enter image description here

但不是第二个输入值: enter image description here

或第三个输入值: enter image description here


Tags: sampleimportasnp方式pltsigma例子
1条回答
网友
1楼 · 发布于 2024-03-29 15:30:28

这是之前讨论过的问题,see

def anno_example(sigma, mu):
    Sample = np.random.normal(mu, sigma, 10000)

    figHS = plt.figure(figsize=(9,6)) 
    axHS = figHS.add_subplot(1, 1, 1)
    n, histbins, patches = axHS.hist(Sample,100, histtype='step', normed=1) 

    axHS.plot(histbins, plt.mlab.normpdf(histbins, mu, sigma))

    axHS.annotate("$\mu=%.3f$ \n $\sigma=%.3f$ \n $N=%i$"%
                  (Sample.mean(), Sample.std(), len(Sample)),
                  xytext=(0.8, 0.85), bbox=dict(boxstyle="sawtooth", fc="w"),
                  xy=(0.8, 0.85), xycoords=axHS.transAxes)
    axHS.annotate(" $\mu=%.3f$ \n $\sigma=%.3f$ \n $N=%s$"%(mu,sigma," "),
                  xytext=(0.6, 0.85), bbox=dict(boxstyle="round", fc="w"),
                  xy=(0.6, 0.85), xycoords=axHS.transAxes)

anno_example(0.12, 0.5)
anno_example(0.1,  0.3)
anno_example(0.05, 0.2)

enter image description hereenter image description hereenter image description here

只要将textcoords="axes fraction"替换为xycoords=axHS.transAxesxycoords="axes fraction"就可以了。你知道吗

相关问题 更多 >