您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 用箭头标记matplotlib直方图bin

5b51 2022/1/14 8:23:26 python 字数 3727 阅读 531 来源 www.jb51.cc/python

我有一个直方图,可以用下面的MWE复制: import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np pd.Series(np.random.normal(0, 100, 1000)).plot(kind='hist', bins=50) 这创建了这样的情节: 那么我如何

概述

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

pd.Series(np.random.normal(0,100,1000)).plot(kind='hist',bins=50)

这创建了这样的情节:

那么我如何用给定整数的箭头标记bin?

例如,见下文,其中箭头标记包含整数300的bin.

编辑:我应该理想地添加箭头的y坐标应该由它标记的条的高度自动设置 – 如果可能的话!

import pandas as pd
import matplotlib.pyplot as plt
#import seaborn as sns
import numpy as np

fig,ax = plt.subplots()
series = pd.Series(np.random.normal(0,1000))
series.plot(kind='hist',bins=50,ax=ax)
ax.annotate("",xy=(300,5),xycoords='data',xytext=(300,20),textcoords='data',arrowprops=dict(arrowstyle="->",connectionstyle="arc3"),)

在这个例子中,我添加一个从坐标(300,20)到(300,5)的箭头.

为了自动将箭头缩放到bin中的值,您可以使用matplotlib hist绘制直方图并获取值,然后使用numpy在哪里找到哪个bin对应于所需位置.

import pandas as pd
import matplotlib.pyplot as plt
#import seaborn as sns
import numpy as np

nbins = 50
labeled_bin = 200

fig,ax = plt.subplots()

series = pd.Series(np.random.normal(0,1000))

## plot the histogram and return the bin position and values
ybins,xbins,_ = ax.hist(series,bins=nbins)

## find out in which bin belongs the position where you want the label
ind_bin = np.where(xbins >= labeled_bin)[0]
if len(ind_bin) > 0 and ind_bin[0] > 0:
    ## get position and value of the bin
    x_bin = xbins[ind_bin[0]-1]/2. + xbins[ind_bin[0]]/2.
    y_bin = ybins[ind_bin[0]-1]
    ## add the arrow
    ax.annotate("",xy=(x_bin,y_bin + 5),xytext=(x_bin,y_bin + 20),)
else:
    print "Labeled bin is outside range"

总结

以上是编程之家为你收集整理的python – 用箭头标记matplotlib直方图bin全部内容,希望文章能够帮你解决python – 用箭头标记matplotlib直方图bin所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶