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

如何在Matplotlib中绘制倒置直方图(含垂直/水平两种形态)

在Matplotlib中绘制倒置直方图的实现方法

没问题,这两个需求都能在Matplotlib里轻松实现,我给你分情况说明并附上可运行的代码示例:

一、绘制基底沿顶部轴向下延伸的垂直倒置直方图

要实现这个效果,核心思路是翻转y轴的方向,或者手动设置直方图的bottom参数让柱子从顶部开始绘制。最简便的方式是用ax.invert_yaxis(),直接将y轴上下颠倒,这样原本向上的柱子就会变成向下延伸了。

示例代码如下:

import matplotlib.pyplot as plt
import numpy as np

# 生成测试数据
np.random.seed(42)
data = np.random.normal(0, 1, 1000)

# 创建画布和轴对象
fig, ax = plt.subplots()

# 绘制普通垂直直方图
n, bins, patches = ax.hist(data, bins=30, color='#1f77b4')

# 翻转y轴,实现柱子向下延伸
ax.invert_yaxis()

# 添加标签和标题,让图表更清晰
ax.set_xlabel('数值')
ax.set_ylabel('频数')
ax.set_title('基底沿顶部轴向下的垂直倒置直方图')

plt.tight_layout()
plt.show()

如果你想更精准控制柱子的起始位置(比如不从顶部边缘开始),可以手动计算bottom参数:把bottom设为y轴的最大值,然后柱子的高度取负数,示例如下:

fig, ax = plt.subplots()
max_y = ax.get_ylim()[1]  # 获取默认y轴的最大值
ax.hist(data, bins=30, bottom=max_y, color='#ff7f0e', height=-n)
ax.set_ylim(max_y, 0)  # 手动设置y轴范围,从max_y到0
plt.show()

二、让水平直方图的基底位于右侧轴

当使用orientation='horizontal'绘制水平直方图时,默认是从左侧轴向右延伸。要让基底在右侧,只需要翻转x轴的方向即可,用ax.invert_xaxis()就能实现。

示例代码:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
data = np.random.normal(0, 1, 1000)

fig, ax = plt.subplots()

# 绘制水平直方图
ax.hist(data, bins=30, orientation='horizontal', color='#2ca02c')

# 翻转x轴,让柱子从右侧轴向左延伸
ax.invert_xaxis()

# 设置标签和标题
ax.set_xlabel('频数')
ax.set_ylabel('数值')
ax.set_title('基底位于右侧轴的水平直方图')

plt.tight_layout()
plt.show()

同样,你也可以手动设置left参数来控制起始位置,把left设为x轴的最大值,宽度取负数,效果是一样的:

fig, ax = plt.subplots()
max_x = ax.get_xlim()[1]
n, bins, patches = ax.hist(data, bins=30, orientation='horizontal', left=max_x, width=-n)
ax.set_xlim(max_x, 0)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:31:30