如何实现matplotlib径向渐变背景

2024-06-03 03:00:55 发布

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

我正在尝试将matplotlib背景设置为:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

ticks = ["Low", "Moderate", "High"]
plt.xlabel(r"x $\longrightarrow$", fontsize=14)
plt.ylabel(r"y $\longrightarrow$", fontsize=14)
plotlim = plt.xlim() + plt.ylim()
print(plotlim)
ax.imshow([[1, 1], [0, 0]],
          cmap=plt.cm.Reds,
          interpolation='bicubic',
          extent=plotlim)
plt.xticks(np.arange(len(ticks)) / 2, ticks, fontsize=14)
plt.yticks(np.arange(len(ticks)) / 2,
           ticks,
           rotation='90',
           ha='center',
           fontsize=14)
plt.show()

问题是这是沿着y-axis给出梯度,而我想要一个径向梯度,类似:enter image description here


Tags: importlenmatplotlibasnpfigpltax
1条回答
网友
1楼 · 发布于 2024-06-03 03:00:55

我认为你只需要调整你正在插值的矩阵,使该矩阵中的梯度指向uppper右角:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

ticks = ["Low", "Moderate", "High"]
plt.xlabel(r"x $\longrightarrow$", fontsize=14)
plt.ylabel(r"y $\longrightarrow$", fontsize=14)
plotlim = plt.xlim() + plt.ylim()
print(plotlim)
ax.imshow([[0.5, 0.5, 0.5], [0, 0.5, 0.5], [0, 0, 0.5]],
          cmap=plt.cm.Reds,
          interpolation='bicubic',
          extent=plotlim, vmin=0, vmax=1)
plt.xticks(np.arange(len(ticks)) / 2, ticks, fontsize=14)
plt.yticks(np.arange(len(ticks)) / 2,
           ticks,
           rotation='90',
           ha='center',
           fontsize=14)

fig.savefig("test.png")

这将给出以下图片:

enter image description here

编辑:

您也可以在不进行插值的情况下建立渐变,以获得一个漂亮的圆形渐变:

x = np.linspace(0, 1, 256)
y = np.linspace(1, 0, 256)

xArray, yArray = np.meshgrid(x, y)
plotArray = np.sqrt(xArray**2 + yArray**2)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(plotArray,
          cmap=plt.cm.Reds,
          vmin=0,
          vmax=1)

enter image description here

相关问题 更多 >