You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

散点图结合直方图坐标轴并按密度着色的实现问题

解决密度着色散点图+边缘分布图的组合问题

我明白你遇到的困扰了——想把密度着色的散点图和左侧/底部布局的边缘分布图结合,但加z=c参数时直接报错对吧?其实问题出在参数用错了,再加上子图布局需要一点点调整,我给你整理了一套完整的可运行方案,直接就能用:

完整代码示例

from scipy.stats import gaussian_kde
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

# 生成示例数据(和你的数据逻辑一致)
np.random.seed(42)  # 固定随机种子,方便复现结果
x = np.random.normal(0, 1, 500)
y = x + 0.3 * np.random.normal(0, 1, 500)

# 计算每个点的密度值(用来给散点着色)
xy_coords = np.vstack([x, y])
density = gaussian_kde(xy_coords)(xy_coords)
# 按密度排序:让高密度点在上方显示,避免被遮挡(可选但实用)
sorted_idx = density.argsort()
x_sorted, y_sorted, density_sorted = x[sorted_idx], y[sorted_idx], density[sorted_idx]

# 创建复合子图布局:主散点图(中间)+ 左侧y边缘图 + 底部x边缘图
fig = plt.figure(figsize=(8, 8))

# 主图(中间区域)
ax_main = fig.add_subplot(111)
# 左侧y轴边缘分布图(和主图共享y轴)
ax_y_dist = fig.add_subplot(121, sharey=ax_main)
# 底部x轴边缘分布图(和主图共享x轴)
ax_x_dist = fig.add_subplot(224, sharex=ax_main)

# 绘制主散点图:这里用c参数绑定密度值(你之前错用了z!)
scatter_plot = ax_main.scatter(
    x_sorted, y_sorted, 
    c=density_sorted,  # 核心:用c指定颜色映射的数值,不是z!
    s=20, cmap='viridis', alpha=0.7
)

# 绘制左侧y轴边缘分布图(直方图+密度曲线)
ax_y_dist.hist(y, bins=20, orientation='horizontal', density=True, color='lightblue', alpha=0.7)
kde_y = gaussian_kde(y)
y_range = np.linspace(y.min(), y.max(), 1000)
ax_y_dist.plot(kde_y(y_range), y_range, color='darkblue')
# 隐藏左侧轴的x刻度/标签,避免重复冗余
ax_y_dist.set_xticks([])
ax_y_dist.set_xlabel('')

# 绘制底部x轴边缘分布图(直方图+密度曲线)
ax_x_dist.hist(x, bins=20, density=True, color='lightgreen', alpha=0.7)
kde_x = gaussian_kde(x)
x_range = np.linspace(x.min(), x.max(), 1000)
ax_x_dist.plot(x_range, kde_x(x_range), color='darkgreen')
# 隐藏底部轴的y刻度/标签,让布局更整洁
ax_x_dist.set_yticks([])
ax_x_dist.set_ylabel('')

# 给主图添加标签
ax_main.set_xlabel('X Value')
ax_main.set_ylabel('Y Value')

# 添加密度对应的颜色条
divider = make_axes_locatable(ax_main)
cax = divider.append_axes("right", size="5%", pad=0.1)
plt.colorbar(scatter_plot, cax=cax, label='Point Density')

# 调整子图间距,避免元素重叠
plt.tight_layout()
plt.show()

关键问题解析&优化点

  • 报错核心原因:你用了z=c,但matplotlib的scatter函数是用c参数来指定颜色映射的数值,z是专门给3D散点图用的z轴坐标参数,参数用错自然会报错,改成c=density_sorted就解决了。
  • 子图布局优化:用sharey和sharex让边缘图和主图的坐标轴范围保持一致,避免视觉错位;同时隐藏重复的刻度标签,让整体布局更简洁。
  • 视觉效果提升:按密度排序后,高密度的点会显示在最上层,不会被低密度点遮挡,能更清晰看到数据密集区域。

内容的提问来源于stack exchange,提问作者Eruditio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:46:55