科研论文配图的绘制与配色基础 -- 直方图概念和绘制方法

直方图

在 Matplotlib 中,我们可使用 axes.Axes.hist() 函数绘制直方图

在 axes.Axes.hist() 函数中,参数 x 为要绘制的样本数据;参数 bins 用于定义分布区间,该参数的值可设置成整数、给定数值序列或字符串,默认为数值类型且值
为 10。

当参数 bins 的值为整数时,定义范围内等宽bin 的数量。

当参数 bins 的值为自定义数值序列时,定义 bin 边缘数值,包括第一个 bin 的左边缘和最后一个 bin 的右边缘。

注意,在上述这种情况下,bin 的间距可能不相等。

当参数 bins 的值为字符串类型时,可选“auto”“fd”“rice”和“sqrt”等值

axes.Axes.hist() 函数的参数 density对应的值为布尔类型,该参数决定绘图结果是否为密度图,默认值为 False。
在这里插入图片描述

绘制代码:
a - Matplotlib绘制直方图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams["ytick.right"] = False
hist_data = pd.read_excel(r"/单变量图表绘制/柱形图绘制数.xlsx")
hist_x_data = hist_data["hist_data"].values
bins = np.arange(0.0,1.5,0.1)
fig,ax = plt.subplots(figsize = (4,3.5),dpi = 100)
hist = ax.hist(x = hist_x_data, bins = bins,
color = "#3F3F3F", edgecolor = 'black',
rwidth = 0.8)
ax.tick_params(axis = "x",which = "minor",top = False,
bottom = False)
ax.set_xticks(np.arange(0,1.4,0.1))
ax.set_yticks(np.arange(0.,2500,400))
ax.set_xlim(-.05,1.3)
ax.set_ylim(0.0,2500)
ax.set_xlabel('Values', )
ax.set_ylabel('Frequency')
plt.show()

b- ProPlot 绘制直方图

import proplot as pplt 
from proplot import rc
rc["axes.labelsize"] = 15
rc['tick.labelsize'] = 12
rc["suptitle.size"] = 15
fig = pplt.figure(figsize=(3.5,3))
ax = fig.subplot()
ax.format(abc = 'a.', abcloc = 'ur', abcsize = 16,
xlabel = 'Values', ylabel = 'Frequency',
xlim = (-.05,1.3), ylim=(0,2500))
hist = ax.hist(x = hist_x_data, bins = bins,
color = "#3F3F3F",
edgecolor = 'black', rwidth = 0.8)

在这里插入图片描述

上图绘制方法:

import numpy as np
import pandas as pd
from scipy.stats import norm
import matplotlib.pyplot as plt
hist_data02 = pd.read_csv(r"\单变量图表绘制\\直方图绘制02.csv") 
bins=15
hist_x_data = hist_data02["hist_data"].values
Median = np.median(hist_x_data)
mu,std = norm.fit(hist_x_data)
fig,ax = plt.subplots(figsize=(5,3.5),dpi=100)
hist = ax.hist(x=hist_x_data, bins=bins,color="gray",
edgecolor ='black',lw=.5)
# 绘制正态分布曲线(Plot the PDF)
xmin, xmax = min(hist_x_data),max(hist_x_data)
x = np.linspace(xmin, xmax, 100) # 100为随机选择,值越大,绘制曲线越密集
p = norm.pdf(x, mu, std)
N = len(hist_x_data)
bin_width = (x.max() - x.min()) / bins
ax.plot(x, p*N*bin_width,linewidth=1,color="r",
label="Normal Distribution Curve")
# 添加均值线
ax.axvline(x=Median,ls="--",lw=1.2,color="b",
label="Median Line")
ax.set_xlabel('Values')
ax.set_ylabel('Count')
ax.legend(frameon=False)
plt.show()

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值