复现顶刊高频图,换数据可用!
本期主角-2D histogram!
在数据分析中,特别是在处理大量散点数据时,2D直方图(2D histogram)能有效避免散点图过于拥挤的问题,帮助我们更好地发现数据之间的潜在关系。
Python matplotlib可轻松制作2D直方图!
数据准备
这里分享一个matplotlib实现案例,使用“3.2.8 data_2dhist数据集”。
import pandas as pd
data_2dhist = pd.read_csv('matplotlib_data/2dhist.csv')
matplotlib绘图
# 16.1_01
# -*- encoding: utf-8 -*-
'''
未经过允许禁止转载!
'''
#核心代码
for i, ax in enumerate(axes.flat):
x, y = data_2dhist['x'][i * len(data_2dhist) // 6:(i + 1) *
len(data_2dhist) //
6], data_2dhist['y'][i * len(data_2dhist) //
6:(i + 1) *
len(data_2dhist) // 6]
slope, intercept, corr, bias, rmse = calculate_stats_and_fit(
x, y) #calculate_stats_and_fit计算统计信息和拟合趋势线
hist = ax.hist2d(x, y, bins=100, norm=LogNorm(),
cmap="Spectral_r") # hist2d绘制散点密度图
ax.plot([-5, 10], [-5, 10],
color="red",
linestyle="--",
linewidth=1.5,
label="1:1 line") # 添加y=x参考线 trend_x = np.linspace(-2, 8, 100)
trend_y = slope * trend_x + intercept
ax.plot(trend_x,
trend_y,
color="black",
linestyle="--",
linewidth=1.5,
label="Fitted Line") # 添加拟合趋势线
stats_text = (f"N = {len(x):,}n"
f"Bias = {bias:.2f}n"
f"RMSE = {rmse:.2f}n"
f"R = {corr:.2f}n"
f"Slope = {slope:.2f}")
ax.text(-4,
9,
stats_text,
fontsize=12,
verticalalignment="top",
bbox=dict(facecolor="white", alpha=0.8)) # 添加统计信息
x_labels = [f"观察值{i+1}" for i in range(6)] # 设置x轴标题
ax.set_xlabel(x_labels[i], fontsize=14)
ax.set_xlim(-5, 10) # 设置x轴范围
y_labels = [f"估计值{i+1}" for i in range(6)] # 设置y轴标题
ax.set_ylabel(y_labels[i], fontsize=14)
ax.set_ylim(-5, 10)
ax.legend(loc="lower right", fontsize=12) # 设置图例
cbar = fig.colorbar(hist[3], ax=axes, fraction=0.04, pad=0.05) # 设置colorbar
cbar.set_label("Density", fontsize=14)
plt.show()
-END-
本期内容「绘图数据+代码+代码详细解释」已上传:👉Python matplotlib保姆级教程
加入学习