如何用Datafram设置子图直方图的多个均值

2024-06-12 09:51:24 发布

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

如果我使用具有多个头的数据帧的pd.DataFrame.hist()函数,那么python将绘制多个直方图。你知道吗

我想用plt.axvline函数和数据帧的平均值来绘制平均值。这不管用

我已经用一个数据帧的一个头试过了,而且成功了。你知道吗

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()

我现在如何将此应用于多个?但我不想让他们各自在一个单独的情节里。你知道吗


Tags: the数据函数dataframedf绘制plt直方图
1条回答
网友
1楼 · 发布于 2024-06-12 09:51:24

DataFrame.hist()返回其中的matplotlib.AxesSubplotnumpy.ndarray。如果您有多个列,那么它很可能返回一个numpy.ndarray的2Dmatplotlib.AxesSubplot。可以使用这些AxesSubplot在每个子图中绘制线。你知道吗

演示:

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>

enter image description here

相关问题 更多 >