简体   繁体   English

如何使用Pandas Dataframe在子图直方图中设置多个平均值

[英]How to set multiple mean values in subplotted histograms with pandas Dataframe

If I use the pd.DataFrame.hist() func of a DataFrame with multiple headers, then python will plot multiple histograms. 如果我使用具有多个标头的DataFrame的pd.DataFrame.hist()函数,则python将绘制多个直方图。

I wanted to plot the mean with the plt.axvline function with the mean of the dataframe. 我想用plt.axvline函数用数据帧的平均值绘制平均值。 This is not working 这不行

I have already tried it with only one header of a dataframe and it worked. 我已经尝试过只使用一个数据帧头,并且它可以工作。

def plot_HistOfDailyReturn(p_df, p_bins=10):

    """plots the histogram of the daily returns"""                          
    df1 = pd.DataFrame(p_df['HCP'])                           
    df1.hist(bins=p_bins)
    plt.axvline(df1['HCP'].mean(), color='w', linestyle='dashed', linewidth=2)
    plt.show()

How can I now apply this to several ones? 我现在如何将其应用于几个? But I don't want want them to be each in a seperate plot. 但我不想让他们每个人都处于单独的情节中。

DataFrame.hist() returns a matplotlib.AxesSubplot or numpy.ndarray of them. DataFrame.hist()返回其中的matplotlib.AxesSubplotnumpy.ndarray If you have multiple columns, then most probably it'll return a 2D numpy.ndarray of matplotlib.AxesSubplot . 如果您有多列,则很可能会返回matplotlib.AxesSubplot的2D numpy.ndarray You can use those AxesSubplot's in order to draw lines in each subplot. 您可以使用这些AxesSubplot来在每个子图中绘制线条。

Demo: 演示:

In [199]: data = pd.DataFrame(np.random.randint(100, size=(1000,4)), columns=list("abcd"))

In [200]: data.shape
Out[200]: (1000, 4)

In [201]: (a, b), (c, d) = data.hist(bins=100, alpha=0.8, figsize=(12, 8))

In [202]: a.axvline(data["a"].mean(), color='orange', linestyle='dashed', linewidth=2)
Out[202]: <matplotlib.lines.Line2D at 0x149c220a4e0>

In [203]: b.axvline(data["b"].mean(), color='orange', linestyle='dashed', linewidth=2)
Out[203]: <matplotlib.lines.Line2D at 0x149c220aa58>

In [204]: c.axvline(data["c"].mean(), color='orange', linestyle='dashed', linewidth=2)
Out[204]: <matplotlib.lines.Line2D at 0x149c098f5f8>

In [205]: d.axvline(data["d"].mean(), color='orange', linestyle='dashed', linewidth=2)
Out[205]: <matplotlib.lines.Line2D at 0x149c222d550>

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM