用箭头标记 matplotlib 直方图箱 [英] Labelling a matplotlib histogram bin with an arrow

查看:36
本文介绍了用箭头标记 matplotlib 直方图箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个直方图,可以用下面的 MWE 复制:

I have a histogram plot which could be replicated with the MWE below:

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)

哪个创建了这样的情节:

Which creates a plot like this:

然后我该如何用箭头标记给定整数的垃圾箱?

How would I then go about labelling the bin with an arrow for a given integer?

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

For example see below, where an arrow labels the bin containing the integer 300.

理想情况下,我应该添加箭头的y坐标,该坐标应通过其所标记的条的高度自动设置-可能的话!

I should add ideally the y coordinates of the arrow should be set automatically by the height of the bar it is labelling - if possible!

推荐答案

您可以使用注释添加箭头:

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, 100, 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).

In this example, I added an arrow that goes from coordinates (300, 20) to (300, 5).

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

In order to automatically scale your arrow to the value in the bin, you can use matplotlib hist to plot the histogram and get the values back and then use numpy where to find which bin corresponds to the desired position.

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, 100, 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), xycoords='data',
                xytext=(x_bin, y_bin + 20), textcoords='data',
                arrowprops=dict(arrowstyle="->",
                                connectionstyle="arc3"),
                                )
else:
    print "Labeled bin is outside range"

这篇关于用箭头标记 matplotlib 直方图箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆