Matplotlib直方图通过常数因子缩放y轴

问题描述 投票:3回答:2

我在直方图中绘制一些值并想要缩放y轴,但我只想找到标准化y轴值或以对数方式缩放它们的方法。我的值是100ps时间步长,我希望将每个y轴值乘以0.1,以获得更好且更容易理解的ns步长。

如何在直方图中缩放y轴值?

n, bins, patches = plt.hist(values1, 50, facecolor='blue', alpha=0.9, label="Sample1",align='left')
n, bins, patches = plt.hist(values2, 50, facecolor='red', alpha=0.9, label="Sample2",align='left')
plt.xlabel('value')
plt.ylabel('time [100ps]')
plt.title('')
plt.axis([-200, 200, 0, 180])


plt.legend()
plt.show()

在该图中,y轴上的10表示1ns:

30 means 3ns

python matplotlib
2个回答
1
投票

最简单的方法是定义轴,然后乘以轴的刻度。例如

fig, ax1 = plt.subplots()
ax1.hist(values1, 50, facecolor='blue', alpha=0.9, label="Sample1",align='left')
y_vals = ax1.get_yticks()
ax1.set_yticklabels(['{:3.0f}%'.format(x * 100) for x in y_vals])
plt.show()

0
投票

我要解决的方法非常简单:在绘制之前,只需将数组values1和values2乘以0.1即可。

matplotlib中存在日志缩放的原因是日志转换非常常见。对于简单的乘法缩放,可以很容易地将您正在绘制的数组相乘。

编辑:你是对的,我错了,很困惑(没注意到你正在处理直方图)。那么我要做的是使用matplotlib.ticker模块来调整y轴上的刻度。见下文:

# Your code.
n, bins, patches = plt.hist(values1, 50, facecolor='blue', alpha=0.9, label="Sample1",align='left')
n, bins, patches = plt.hist(values2, 50, facecolor='red', alpha=0.9, label="Sample2",align='left')
plt.xlabel('value')
plt.ylabel('time [100ps]')
plt.title('')
plt.axis([-200, 200, 0, 180])
plt.legend()

# My addition.
import matplotlib.ticker as mtick
def div_10(x, *args):
    """
    The function that will you be applied to your y-axis ticks.
    """
    x = float(x)/10
    return "{:.1f}".format(x)    
# Apply to the major ticks of the y-axis the function that you defined. 
ax = plt.gca()       
ax.yaxis.set_major_formatter(mtick.FuncFormatter(div_10))
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.