python - 如何在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()
这是我现在正在生成的情节
解决方案
一个优雅的解决方案是应用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轴上具有原始值的图片( 1000000到 7000000)。
但是如果你运行:
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()
推荐阅读
- wordpress - Iframes not working after enabling SSL Certificate
- python - Python将QtDesigner类作为动态参数传递给外部文件中的类
- r - R Shiny条件面板问题
- react-native - 如何在 React Native 中打开其他移动应用程序?
- javascript - jquery不改变元素的src
- python - 创建一个返回长度的函数
- django - 使用 React native 从 Django AuthTokenSerializer 中提取令牌
- performance - 使用枚举而不是布尔值真的会影响缓存的使用吗?
- html - 是否可以在由单词或文本组成的框周围制作边框?
- python - 如何将十进制提交给 Django API?