直方图Y轴上数量不等

问题描述 投票:0回答:1

我想在 Matplotlib 子图中绘制直方图。我有代码

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]
    plt.hist(x, bins,  alpha=0.65, label='old', edgecolor='black', color='lightgrey')
    plt.ylim= (-500, 500)

plt.show()

结果看起来像这样

如何让Y轴自动显示最大值?

python matplotlib histogram
1个回答
0
投票

在下面的示例中,我首先删除现有的最上面的 y 刻度,然后添加所需的最大刻度值。如果我们不删除现有的蜱虫,它们就足够接近,足以与新的蜱虫重叠,并使标签不清楚。

带有一些可选的额外标签和美观:

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

#Test data
np.random.seed(0)
dfe = pd.DataFrame({'O18ad': np.random.randn(600_000) * 4 - 10})

#Plot
fig = plt.figure(figsize=(5, 4))
ax = fig.add_subplot()  

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]
# A more compact way of defining the bins
bins = np.arange(-20, 2)

bin_counts, _, bars = plt.hist(x, bins,  alpha=0.65, label='old', edgecolor='black', color='lightgrey')

#Remove tick values that are more than the max
#Otherwise there will be overlap issues as they're close
old_yticks = ax.get_yticks()
new_ticks = old_yticks[old_yticks < bin_counts.max()]
#Insert the new maximum tick value
new_ticks = np.append(new_ticks, bin_counts.max())

ax.set_yticks(new_ticks)

#Label axes
ax.set_ylabel('counts')
ax.set_xlabel('bin edge')
ax.set_title('Histogram of "O18ad"\n')

添加条形标签并删除一些刺:

#You could also label the bars
# I've customised it but you could just use ax.bar_label(bars)
ax.bar_label(
    bars,
    fontsize=8, color='tab:red', rotation=90,
    label_type='edge', padding=5, fmt=lambda v: int(round(v, -2))
)

#Remove the top and right spines for aesthetics
[ax.spines[spine].set_visible(False) for spine in ('top', 'right')]

plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.