AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 78020884
Accepted
con
con
Asked: 2024-02-19 21:05:34 +0800 CST2024-02-19 21:05:34 +0800 CST 2024-02-19 21:05:34 +0800 CST

hist2d 绘图时 vmin/vax 未知,直到使用组合颜色条绘图;以前的解决方案不起作用

  • 772

我正在尝试绘制行密度图。具有挑战性的部分是,每个图必须具有相同的色标最小值和最大值,并且我事先不知道最小值和最大值是多少。我必须首先绘制这些值,以便找出最小值和最大值,删除这些图,然后使用确定的最小值/最大值绘制新的图。

像这样的东西,但是使用 hist2d 并按行(来自另一个 SO 页面的图像): 在此输入图像描述

我提出了一个基于How to have one colorbar for all subplots , vmin and vmax in hist2d 的最小工作示例

以及来自“SpinUp __ A Davis”的解决方案,我不知道如何使用真实数据来实现:

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=1, ncols=3)
for ax in axes.flat: # I don't see how to implement this part with real data
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

fig.colorbar(im, ax=axes.ravel().tolist())

plt.show()

但我能想到的最好的办法是这个,这是行不通的:

import matplotlib.pyplot as plt
import numpy as np # only for MWE, not present in real file
# https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hist2d.html

# getting min/max
fig, (ax0,ax1) = plt.subplots(nrows = 2, ncols = 1, sharex = True)
colormax = float("-inf")
colormin = float("inf")

h0 = ax0.hist2d(np.random.random(100), np.random.random(100))
colormax = max(h0[0].max(), colormax)
colormin = min(h0[0].min(), colormin)
h1 = ax1.hist2d(np.random.random(200), np.random.random(200))
colormax = max(h1[0].max(), colormax)
colormin = min(h1[0].min(), colormin)
# starting real plot, not just to get min/max
fig, axes = plt.subplots(nrows = 2, ncols = 1, sharex = True, figsize = (6.4,4.8))
i = 0
h = [h0, h1]
for ax in axes.flat: # I don't see how I can implement this
    im = ax.imshow(h[i], vmin = colormin, vmax = colormax)
    i += 1
fig.colorbar(im, ax= axes.ravel().tolist())
plt.savefig('imshow.debug.png')
python
  • 1 1 个回答
  • 47 Views

1 个回答

  • Voted
  1. Best Answer
    JohanC
    2024-02-20T00:17:44+08:002024-02-20T00:17:44+08:00

    要使用以下命令创建直方图imshow:

    • 您需要获取直方图作为 . 返回的四个值中的第一个ax.hist2d。所以h0, _, _, _ = ax.hist2d(...)
    • 直方图矩阵需要转置,因为它的 x 和 y 交换了。
    • imshow需要origin='lower'在底部具有最低的 y。
    • imshow需要extent=[...]x 和 y 范围。

    由于您似乎希望共享 x 轴(而不是 y 轴),因此需要使用最大 x 范围来计算直方图箱。设置(np.linspace(xmin, xmax, 11), 10)将 x 范围分割为 10 个 bin,并使用默认的 10 个 bin 来表示 y。在示例代码中,x 箱是共享的,而 y 箱是特定于每个图的。

    对相关代码的更改

    下面的测试代码也做了一些修改:

    • turbo颜色图和额外的颜色条可以更好地看到差异
    • Python 的首选循环方式for(列表理解来计算最小值和最大值)
    import matplotlib.pyplot as plt
    from matplotlib.ticker import MaxNLocator
    import numpy as np
    
    # first create some reproducible test data
    np.random.seed(20240219)
    x0 = np.random.random(100)
    y0 = np.random.random(100)
    x1 = np.random.random(100)
    y1 = np.random.random(100)
    xmin = min(x0.min(), x1.min())
    xmax = min(x0.max(), x1.max())
    bins = (np.linspace(xmin, xmax, 11), 10)
    
    # dummy plot to calculate the min and max of the histograms
    fig, (ax0, ax1) = plt.subplots(nrows=2, ncols=1, sharex=True, figsize=(6.4, 4.8))
    h0, _, _, img0 = ax0.hist2d(x0, y0, bins=bins, cmap='turbo')
    cbar0 = fig.colorbar(img0, ax=ax0)
    cbar0.ax.yaxis.set_major_locator(MaxNLocator(integer=True))  # force integer ticks
    
    h1, _, _, img1 = ax1.hist2d(x1, y1, bins=bins, cmap='turbo')
    cbar1 = fig.colorbar(img1, ax=ax1)
    cbar1.ax.yaxis.set_major_locator(MaxNLocator(integer=True))  # force integer ticks
    
    h = [h0, h1]
    colormin = min(hi.min() for hi in h)
    colormax = max(hi.max() for hi in h)
    
    # starting real plot
    fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True, figsize=(6.4, 4.8))
    for ax, hi, yi in zip(axes.flat, h, [y0, y1]):
        im = ax.imshow(hi.T, vmin=colormin, vmax=colormax, origin='lower', aspect='auto',
                       extent=[xmin, xmax, yi.min(), yi.max()], cmap='turbo')
    cbar = fig.colorbar(im, ax=axes.ravel().tolist())
    cbar.ax.yaxis.set_major_locator(MaxNLocator(integer=True))  # force integer ticks
    plt.show()
    

    通过 imshow 具有通用色标的 hist2d

    使用np.histogram2d()

    为了简化代码,可以使用ax.hist2d,来代替 。np.histogram2d这将完成所有计算,而无需创建绘图。

    import matplotlib.pyplot as plt
    from matplotlib.ticker import MaxNLocator
    import numpy as np
    
    # first create some reproducible test data
    np.random.seed(20240219)
    x0 = np.random.random(100) * 10
    y0 = np.random.random(100) * 10
    x1 = np.random.random(100) * 10
    y1 = np.random.random(100) * 10
    xmin = min(x0.min(), x1.min())
    xmax = min(x0.max(), x1.max())
    bins = (np.linspace(xmin, xmax, 11), 10)
    
    h0, _, _ = np.histogram2d(x0, y0, bins=bins)
    h1, _, _ = np.histogram2d(x1, y1, bins=bins)
    
    h = [h0, h1]
    colormin = min(hi.min() for hi in h)
    colormax = max(hi.max() for hi in h)
    
    # starting real plot
    fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True, figsize=(6.4, 4.8))
    for ax, hi, yi in zip(axes.flat, h, [y0, y1]):
        im = ax.imshow(hi.T, vmin=colormin, vmax=colormax, origin='lower', aspect='auto',
                       extent=[xmin, xmax, yi.min(), yi.max()], cmap='turbo')
    cbar = fig.colorbar(im, ax=axes.ravel().tolist())
    cbar.ax.yaxis.set_major_locator(MaxNLocator(integer=True))  # force integer ticks
    plt.show()
    
    • 1

相关问题

  • 如何将 for 循环拆分为 3 个单独的数据框?

  • 如何检查 Pandas DataFrame 中的所有浮点列是否近似相等或接近

  • “load_dataset”如何工作,因为它没有检测示例文件?

  • 为什么 pandas.eval() 字符串比较返回 False

  • Python tkinter/ ttkboostrap dateentry 在只读状态下不起作用

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve