在matplotlib中制作log2缩放的热图 [英] making log2 scaled heatmap in matplotlib
问题描述
我想绘制matplotlib中倍数变化的热图,其中颜色以log2比例绘制,并自定义在色条中显示哪些刻度.我尝试了以下方法:
I want to plot a heatmap of fold changes in matplotlib, where the colors are plotted on a log2 scale, and customize which ticks are shown in the colorbar. I tried the following:
import matplotlib.pylab as plt
import numpy as np
import matplotlib.colors
from matplotlib.colors import SymLogNorm, LogNorm
mat1 = np.clip(np.random.normal(20, 10, [20, 20]), a_min=0, a_max=500)
mat2 = np.clip(np.random.normal(10, 5, [20, 20]), a_min=0, a_max=500)
mat = np.clip(mat1 / mat2, a_min=0, a_max=500)
plt.figure()
print mat
cmap = plt.cm.get_cmap("seismic")
ticks = np.array([1/float(50), 1/float(20), 1, 20, 50])
# how to make these ticks spaced out on a log2 and not log10 scale?
plt.pcolormesh(mat, cmap=cmap, norm=SymLogNorm(linthresh=0.01, vmin=1/50., vmax=50.))
p = plt.colorbar(ticks=ticks)
plt.show()
我希望将1的倍数变化显示为白色,所以我使用了地震色图.
I want fold change of 1 to appear as white so I used the seismic colormap.
问题:如何使颜色以log2的比例而不是log10的比例?刻度线是否也显示为log2值而不是未记录的值?
Question: How can I make the colors spaced in log2 scale, and not log10? And also have the ticks show up as log2 values rather than the unlogged values?
如果我尝试使用LogNorm
而不是SymLogNorm
,则刻度标签和我的刻度不会显示:
If I try to use LogNorm
instead of SymLogNorm
then the tick labels and my ticks do not show up:
# This does not work -- ticks do not show
plt.pcolormesh(mat, cmap=cmap, norm=LogNorm(vmin=1/50., vmax=50.))
p = plt.colorbar(ticks=ticks)
我知道SymLogNorm
用于负数据(我没有).我之所以只使用它,是因为LogNorm
I know SymLogNorm
is meant for negative data (which I don't have). I only used it because of this tick issue with LogNorm
推荐答案
您可以将colorbar
对象的locator
设置为以2为底的LogLocator
.然后,您需要调用p.update_ticks()
.
You could set the locator
of the colorbar
object to a LogLocator
with a base of 2. You then need to call p.update_ticks()
.
plt.pcolormesh(mat, cmap=cmap, norm=SymLogNorm(linthresh=0.01, vmin=1/50., vmax=50.))
p = plt.colorbar()
p.locator=ticker.LogLocator(base=2)
p.update_ticks()
这篇关于在matplotlib中制作log2缩放的热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!