首页 > 解决方案 > 如何在matplotlib中以百万为单位缩放直方图y轴

问题描述

我正在绘制一个直方图,matplotlib但我的y-axis范围是数百万。如何缩放 y 轴以便打印而不是5000000打印5

这是我的代码

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

filename = './norstar10readlength.csv'
df=pd.read_csv(filename, sep=',',header=None)

n, bins, patches = plt.hist(x=df.values, bins=10, color='#0504aa',
                            alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('My Very Own Histogram')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.show()

这是我现在正在生成的情节

l

标签: pythonnumpymatplotlibhistogram

解决方案


一个优雅的解决方案是应用FuncFormatter来格式化y标签。

我使用了以下DataFrame而不是您的源数据:

       Val
0   800000
1  2600000
2  6700000
3  1400000
4  1700000
5  1600000

并制作了条形图。“普通”条形图:

df.Val.plot.bar(rot=0, width=0.75);

生成在y轴上具有原始值的图片( 10000007000000)。

但是如果你运行:

from matplotlib.ticker import FuncFormatter

def lblFormat(n, pos):
    return str(int(n / 1e6))

lblFormatter = FuncFormatter(lblFormat)
ax = df.Val.plot.bar(rot=0, width=0.75)
ax.yaxis.set_major_formatter(lblFormatter)

那么y轴标签是整数(百万):

在此处输入图像描述

所以你可以安排你的代码是这样的:

n, bins, patches = plt.hist(x=df.values, ...)
#
# Other drawing actions, up to "plt.ylim" (including)
#
ax = plt.gca()
ax.yaxis.set_major_formatter(lblFormatter)
plt.show()

推荐阅读