使用hist2d在matplotlib中创建对数线性图

使用hist2d在matplotlib中创建对数线性图

本文介绍了使用hist2d在matplotlib中创建对数线性图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道这是否可以做到.我尝试使用 numpy logspace 显式设置垃圾箱,并且还尝试将 xscale 设置为log".这些选项都不起作用.有没有人试过这个?

I was just wondering if this can be done. I have tried to set the bins explicitly using numpy logspace, and I have also tried to set the xscale to 'log'. Neither of these options work. Has anybody ever tried this?

我只想要带有对数x轴和线性y轴的二维直方图.

I just want a 2d histogram with a log x-axis and a linear y-axis.

推荐答案

无法正常工作的原因是 plt.hist2d 使用了 pcolorfast 方法,这在很大程度上对于大图像更有效,但不支持对数轴.

The reason it's not working correctly is that plt.hist2d uses the pcolorfast method, which is much more efficient for large images, but doesn't support log axes.

要在对数轴上正确运行二维直方图,您需要使用 np.histogram2dax.pcolor 自行制作.但是,这只是额外的一行代码.

To have a 2D histogram that works correctly on log axes, you'll need to make it yourself using np.histogram2d and ax.pcolor. However, it's only one extra line of code.

首先,让我们在线性轴上使用指数间隔的容器:

To start with, let's use exponentially spaced bins on a linear axis:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.random((2, 1000))
x = 10**x

xbins = 10**np.linspace(0, 1, 10)
ybins = np.linspace(0, 1, 10)

fig, ax = plt.subplots()
ax.hist2d(x, y, bins=(xbins, ybins))

plt.show()

好的,一切顺利.让我们看看如果使x轴使用对数刻度会发生什么:

Okay, all well and good. Let's see what happens if we make the x-axis use a log scale:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.random((2, 1000))
x = 10**x

xbins = 10**np.linspace(0, 1, 10)
ybins = np.linspace(0, 1, 10)

fig, ax = plt.subplots()
ax.hist2d(x, y, bins=(xbins, ybins))

ax.set_xscale('log') # <-- Only difference from previous example

plt.show()

请注意,似乎已经应用了对数缩放,但是彩色图像(直方图)没有反映出来.垃圾箱应该是方形的!这不是因为 pcolorfast 创建的艺术家不支持日志轴.

Notice that the log scaling seems to have been applied, but the colored image (the histogram) isn't reflecting it. The bins should appear square! They're not because the artist created by pcolorfast doesn't support log axes.

为了解决这个问题,让我们使用 np.histogram2d(plt.hist2d 在幕后使用什么)制作直方图,然后使用 绘制它pcolormesh (或 pcolor ),它支持日志轴:

To fix this, let's make the histogram using np.histogram2d (what plt.hist2d uses behind-the-scenes), and then plot it using pcolormesh (or pcolor), which does support log axes:

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1977)

x, y = np.random.random((2, 1000))
x = 10**x

xbins = 10**np.linspace(0, 1, 10)
ybins = np.linspace(0, 1, 10)

counts, _, _ = np.histogram2d(x, y, bins=(xbins, ybins))

fig, ax = plt.subplots()
ax.pcolormesh(xbins, ybins, counts.T)

ax.set_xscale('log')

plt.show()

(请注意,这里我们必须转置 counts ,因为 pcolormesh 期望轴的顺序为(Y,X).)

(Note that we have to transpose counts here, because pcolormesh expects the axes to be in the order of (Y, X).)

现在我们得到了我们期望的结果:

Now we get the result we'd expect:

这篇关于使用hist2d在matplotlib中创建对数线性图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 15:15