带lognorm-colorbar级别的matplotlib等高线图

2024-04-19 10:39:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图做一个等高线图与定义的水平和日志规范。下面是一个例子:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
delta = 0.025

x = y = np.arange(0, 3.01, delta)
X, Y = np.meshgrid(x, y)
Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10 * (Z1* Z2)

fig=plt.figure()
ax1 = fig.add_subplot(111)
lvls = np.logspace(-4,0,20)
CF = ax1.contourf(X,Y,Z,
         norm = LogNorm(),
         levels = lvls
        )
CS = ax1.contour(X,Y,Z,
         norm = LogNorm(),
         colors = 'k',
         levels = lvls
        )
cbar = plt.colorbar(CF, ticks=lvls, format='%.4f')
plt.show()

enter image description here 我的问题是:
这些级别的格式应该是:“1x10^-4”、“1.6x10^-4”。。。如何在不手动指定每个级别的情况下执行此操作?

我在Windows7上使用Python2.7.3和MatplotLib1.1.1。


Tags: importmatplotlibasnppltdeltanormalcolors
1条回答
网友
1楼 · 发布于 2024-04-19 10:39:38

here中,我找到了一种似乎适合您问题的方法:

from matplotlib.ticker import LogFormatter
l_f = LogFormatter(10, labelOnlyBase=False)
cbar = plt.colorbar(CF, ticks=lvls, format=l_f)

将给予:

enter image description here

请注意,刻度之间的间距确实是按对数刻度。。。

相关问题 更多 >