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

前端之家收集整理的这篇文章主要介绍了python – 用箭头标记matplotlib直方图bin前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个直方图,可以用下面的MWE复制:
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import seaborn as sns
  4. import numpy as np
  5.  
  6. pd.Series(np.random.normal(0,100,1000)).plot(kind='hist',bins=50)

这创建了这样的情节:

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

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

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

解决方法

您可以使用注释添加箭头:
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. #import seaborn as sns
  4. import numpy as np
  5.  
  6. fig,ax = plt.subplots()
  7. series = pd.Series(np.random.normal(0,1000))
  8. series.plot(kind='hist',bins=50,ax=ax)
  9. 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对应于所需位置.

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. #import seaborn as sns
  4. import numpy as np
  5.  
  6. nbins = 50
  7. labeled_bin = 200
  8.  
  9. fig,ax = plt.subplots()
  10.  
  11. series = pd.Series(np.random.normal(0,1000))
  12.  
  13. ## plot the histogram and return the bin position and values
  14. ybins,xbins,_ = ax.hist(series,bins=nbins)
  15.  
  16. ## find out in which bin belongs the position where you want the label
  17. ind_bin = np.where(xbins >= labeled_bin)[0]
  18. if len(ind_bin) > 0 and ind_bin[0] > 0:
  19. ## get position and value of the bin
  20. x_bin = xbins[ind_bin[0]-1]/2. + xbins[ind_bin[0]]/2.
  21. y_bin = ybins[ind_bin[0]-1]
  22. ## add the arrow
  23. ax.annotate("",xy=(x_bin,y_bin + 5),xytext=(x_bin,y_bin + 20),)
  24. else:
  25. print "Labeled bin is outside range"

猜你在找的Python相关文章