首页 > 解决方案 > 如何使用 matplotlib 重新缩放轴

问题描述

我可以创建一个情节如下:

import matplotlib.pyplot as plt    

image = [[0.0, 0.0, 0.0, 0.0, 0.0],
         [0.2, 0.0, 0.1, 0.0 ,0.0],
         [0.0, 0.0, 0.3, 0.0 ,0.0],
         [0.0, 0.0, 0.0, 0.0, 0.0],
         [0.0, 0.0, 0.0, 0.0, 0.0]]

print(image)
plt.imshow(image, cmap="plasma", interpolation='nearest')
plt.colorbar()
plt.xlabel("axis x")
plt.ylabel("axis y")
plt.show()

但是我怎样才能改变轴本身,即我想将例如 x 轴转换为不同的范围。例如,上面代码生成的绘图上的值 0 对应于值 -4.8573。上图中的值“4”对应于值 12.443。

然后我想有一个刻度在 -5、0、10、15 左右的轴。我怎样才能做到这一点?

实轴值可以通过下式计算

x_real = a + x * b

标签: pythonmatplotlibdata-visualizationvisualizationaxis

解决方案


要自动插值,您可以执行以下操作:

import matplotlib.pyplot as plt   
import math
import numpy as np

n=5 

image = [[0.0, 0.0, 0.0, 0.0, 0.0],
         [0.2, 0.0, 0.1, 0.0 ,0.0],
         [0.0, 0.0, 0.3, 0.0 ,0.0],
         [0.0, 0.0, 0.0, 0.0, 0.0],
         [0.0, 0.0, 0.0, 0.0, 0.0]]

print(image)
plt.imshow(image, cmap="plasma", interpolation='nearest')
plt.colorbar()

x = [37.59390426045407, 38.00530354847739, 38.28412244348653, 38.74871247986305, 38.73175910429809, 38.869008864244016, 39.188234404976555, 39.92835838352555, 40.881394113153334, 41.686136269465884]
y = [0.1305391767832006, 0.13764519613447768, 0.14573326951792354, 0.15090729309032114, 0.16355823707239897, 0.17327106424274763, 0.17749746339532224, 0.17310384614773594, 0.16545780437882962, 0.1604752704890856]


def ceil_power_of_10(n):
    exp = math.log(n, 10)
    exp = math.ceil(exp)
    return 10**exp


x0 = min(x)
x1 = max(x)

y0 = min(y)
y1 = max(y)

# Fill the 2D array
dx = (x1 - x0)/n
dy = (y1 - y0)/n

dx_steps = ceil_power_of_10(dx)
dy_steps = ceil_power_of_10(dy)

dx_steps_alpha = round((math.ceil(x1/dx_steps)*dx_steps) - (math.floor(x0/dx_steps)*dx_steps) )
dy_steps_alpha = round(((math.ceil(y1/dy_steps)*dy_steps) - (math.floor(y0/dy_steps)*dy_steps) ) / dy_steps)


x_new = np.linspace((math.floor(x0/dx_steps)*dx_steps), (math.ceil(x1/dx_steps)*dx_steps), dx_steps_alpha, endpoint=False)
y_new = np.linspace((math.floor(y0/dy_steps)*dy_steps), (math.ceil(y1/dy_steps)*dy_steps), dy_steps_alpha, endpoint=False)

labels_x = x_new
labels_x = [round(x,dx_steps) for x in labels_x]
positions_x = list(range(0, len(labels_x)))
labels_y = y_new
labels_y = [round(y/dy_steps) * dy_steps for y in labels_y]
positions_y = list(range(0, len(labels_y)))
# In the end, used to create a surface plot
plt.imshow(image, cmap="plasma", interpolation='nearest')
plt.xticks(positions_x, labels_x)
plt.yticks(positions_y, labels_y)
plt.xlabel("axis x")
plt.ylabel("axis y")
plt.show()

在此处输入图像描述


推荐阅读