You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib子图直方图Y轴最大值自动显示问题求助

Matplotlib子图直方图Y轴最大值自动显示问题求助

大家好,我最近在用Matplotlib绘制子图里的直方图时遇到了个小问题,想请教下各位怎么解决:我希望Y轴能自动把直方图的峰值(也就是bin_counts的最大值)显示出来,但目前自己写的代码处理起来很生硬,效果也达不到预期,想问问有没有更合理的实现方式。

先贴一下我的代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

def plot_Diff(data):
    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(423)
    x = dfe['O18ad']
    bins=[-20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1]
    
    old_yticks = ax.get_yticks()
    bin_counts, _, bars = plt.hist(x, bins,  alpha=0.65, label='old', edgecolor='black', color='lightgrey')
    
    new_ticks = old_yticks[old_yticks < bin_counts.max()]
    new_ticks = np.append(new_ticks, bin_counts.max())
    ax.set_yticks(new_ticks)
    
    plt.show()

我的数据示例(截取了首尾部分):

0        -4.268475
1        -4.265793
2        -4.263120
3        -4.260457
4        -4.257803
...
359995   -7.813345
359996   -7.821394
359997   -7.773479
359998   -7.807605
359999   -7.797769

我原本的实现效果不太理想,之后参考了一个方法修改了代码,但结果还是不对。想请教下,怎么才能让Y轴自动把直方图的最大值显示出来呢?

备注:内容来源于stack exchange,提问作者Weiss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 11:34:31