问题描述
我有一个分布大的对数数据集.我想制作一个热图,所以我做一个2D直方图并将其传递给绘图.因为数据是对数的,所以我将数据的日志传递给直方图.但是,当我绘制图时,我希望恢复轴(即10 ^ hist bin值)和对数轴.如果我将轴设置为对数样式,则图像看起来将全部倾斜.从我将数据传递到直方图以来,数据已经被记录"了,所以我不希望图像受到影响,而只是轴受到影响.因此,在下面的示例中,我希望图像在左侧,轴在右侧.
I have a large data set that is logarithmic in distribution. I want to make a heat map, so I do a 2D histogram and pass that to implot. Because the data is logarithmic, I am passing the log of the data to the histogram. When I make the plot, however, I want the axis to be restored (ie 10^hist bin values) and log axes. If I set the axis to log style, then the image looks all skewed. The data is already 'logged' from when I passed it to the histogram, so I don't want the image affected, just the axis. So, in the below example, I want the image on the left with the axis on the right.
我想我可以用假的重叠轴来做到这一点,但是如果有更好的方法,我不喜欢那样做……
I guess I could do it with a fake overlayed axis, but I don't like to do that sort of thing if there's a better way...
import numpy as np
import matplotlib.pyplot as plt
x=10**np.random.random(10000)*5
y=10**np.random.random(10000)*5
samps, xedges, yedges = np.histogram2d(np.log10(y), np.log10(x), bins=50)
ax = plt.subplot(121)
plt.imshow(samps, extent=[0,5,0,5])
plt.xlabel('Log10 X')
plt.ylabel('Log10 Y')
ax = plt.subplot(122)
plt.imshow(samps, extent=[10**0,10**5,10**0,10**5])
plt.xlabel('X')
plt.ylabel('Y')
plt.xscale('log')
plt.yscale('log')
plt.show()
推荐答案
您需要使用自定义格式化程序.这是来自matplotlib文档的示例: https://matplotlib.org/examples/pylab_examples/custom_ticker1.html
You need to use a custom formatter. Here's an example from the matplotlib docs:https://matplotlib.org/examples/pylab_examples/custom_ticker1.html
我倾向于使用FuncFormatter
作为示例.主要技巧是您的函数需要使用参数x
和pos
.老实说,我不知道pos
是干什么的.也许甚至没有故意,但是您可以使用FuncFormatter
作为装饰器,这是我在下面所做的事情:
I tend to use FuncFormatter
as the example does. The main trick is that your function need to take to arguments x
and pos
. I honestly don't know what pos
is for. Perhaps no even intentionally, but you can use FuncFormatter
as a decorator, which is what I do below:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
@plt.FuncFormatter
def fake_log(x, pos):
'The two args are the value and tick position'
return r'$10^{%d}$' % (x)
x=10**np.random.random(10000)*5
y=10**np.random.random(10000)*5
samps, xedges, yedges = np.histogram2d(np.log10(y), np.log10(x), bins=50)
fig, (ax1) = plt.subplots()
ax1.imshow(samps, extent=[0, 5, 0, 5])
ax1.xaxis.set_major_formatter(fake_log)
ax1.yaxis.set_major_formatter(fake_log)
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
这篇关于如何在没有对数缩放图像的情况下应用对数轴标签(matplotlib imshow)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!