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

如何调整六边形分箱图(hexbin plot)的坐标轴标签字体大小?

当然可以!不管你用的是matplotlib原生的hexbin函数,还是借助seaborn来绘制六边形分箱图,都能轻松调整坐标轴标签的字体大小。下面分两种常见场景给你具体的实现方法:

1. Matplotlib原生实现

先看一个基础的hexbin绘制示例,在设置坐标轴标签时直接指定fontsize参数即可:

import matplotlib.pyplot as plt
import numpy as np

# 生成示例数据
x = np.random.randn(10000)
y = np.random.randn(10000)

# 绘制hexbin图
plt.hexbin(x, y, gridsize=30, cmap='viridis')
plt.colorbar(label='Count')

# 设置坐标轴标签并指定字体大小
plt.xlabel('X轴标签', fontsize=14)  # 这里的fontsize可根据需求调整,比如12、16等
plt.ylabel('Y轴标签', fontsize=14)

plt.show()

如果你习惯用面向对象的绘图方式(更适合复杂绘图场景),可以通过轴对象来设置:

fig, ax = plt.subplots()
ax.hexbin(x, y, gridsize=30, cmap='viridis')
ax.set_xlabel('X轴标签', fontsize=14)
ax.set_ylabel('Y轴标签', fontsize=14)
ax.figure.colorbar(ax.collections[0], label='Count')

plt.show()
2. Seaborn场景(比如jointplot)

如果你用seaborn的jointplot绘制带hexbin的联合图,需要先获取对应的轴对象,再修改标签字体大小:

import seaborn as sns
import numpy as np

x = np.random.randn(10000)
y = np.random.randn(10000)

# 绘制hexbin联合图
g = sns.jointplot(x=x, y=y, kind='hex', gridsize=30, cmap='viridis')

# 修改主坐标轴的标签字体大小
g.ax_joint.set_xlabel('X轴标签', fontsize=14)
g.ax_joint.set_ylabel('Y轴标签', fontsize=14)

# 若需要修改边缘直方图的标签,也可用类似方式
g.ax_marg_x.set_xlabel('边缘X分布', fontsize=12)
g.ax_marg_y.set_ylabel('边缘Y分布', fontsize=12)

plt.show()
进阶技巧:全局设置

如果你想让所有绘图的坐标轴标签都默认使用指定字号,可以在代码开头设置matplotlib的全局参数:

import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14  # 全局设置坐标轴标签字体大小为14

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:10:52