【代码模版】matplotlib直方图绘制(持续更新)
程序员文章站
2022-07-14 16:29:11
...
1. 基本直方图绘制
fig, ax = plt.subplots(figsize=(12, 8))
ax.hist(DF['column_name'], bins=x); # bins指定分为多少组
ax.set_xlabel('name');
ax.set_ylabel('name');
ax.set_title('name')
最终效果图:
2. log化数据后的直方图绘制
def plot_hist(df, variable, bins=20, xlabel=None, by=None,
ylabel=None, title=None, logx=False, ax=None):
if not ax:
fig, ax = plt.subplots(figsize=(12,8))
if logx:
if df[variable].min() <=0:
df[variable] = df[variable] - df[variable].min() + 1
print('Warning: data <=0 exists, data transformed by %0.2g before plotting' % (- df[variable].min() + 1))
bins = np.logspace(np.log10(df[variable].min()),
np.log10(df[variable].max()), bins)
ax.set_xscale("log")
ax.hist(df[variable].dropna().values, bins=bins);
if xlabel:
ax.set_xlabel(xlabel);
if ylabel:
ax.set_ylabel(ylabel);
if title:
ax.set_title(title);
return ax
# 函数调用
plot_hist(DF, 'column_name', bins=x, logx=True,
xlabel='name', ylabel='name',
title='name')
最终效果图:
上一篇: GCD中常用的函数