基于数组和colormap的matplotlib背景着色

esbemjvw  于 2023-11-22  发布在  其他
关注(0)|答案(2)|浏览(85)

我想知道是否有可能根据绘制的数据对典型matplotlib图的背景进行阴影处理。
为了简单起见,假设我们有:

x=arange(1,5,0.01)
y=sin(x)
plot(x,y)

字符串
那么,是否可以根据y值对轴的背景进行着色?
着色可以通过将包含x和y的数组传递给imshow来实现,例如:

imshow(array, cmap='hot')


尽管我想在这个imshow图上有一个x和y的线图。
请问可以吗?

bbmckpt7

bbmckpt71#

当然有可能:

x = arange(1,5,0.01)
yarr = vstack((x,))
y = sin(x)

imshow(yarr, extent=(min(x),max(x), min(y),max(y)), cmap=cm.hot)
plot(x, y, color='cornflowerblue',lw=4)

字符串
extent关键字将图像的限制与打印数据相匹配。
这将给你给予:

wztqucjr

wztqucjr2#

也可以在所需位置(例如x=5)Resulting Figure中包含您自己的发散色图,其中发散点

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

## Create colormap for J background
low = (np.array([255,244,132])/255).tolist() # 
high = (np.array([84,236,231])/255).tolist() # 

color1 = [low, (1,1,1)] #from low to white
color2= [(1,1,1), high ] # from white to high 

cm1 = LinearSegmentedColormap.from_list("Custom", color1, N=100)
cm2 = LinearSegmentedColormap.from_list("Custom", color2, N=100)

## Create a figure and axis for the main plot
fig, ax1 = plt.subplots()
x_data = np.linspace(0, 10, 100)
y_data = np.sin(x_data)
plt.plot(x_data, y_data)

## poit for 'white'
div_point_x =  5

## scale the imshow for the plot area
xp = ax1.get_xlim()
yp = ax1.get_ylim()

# color scale for both parts of the imshow
x1 = np.linspace(xp[0], div_point_x, 256)
x2 = np.linspace(div_point_x, xp[1], 256)
y1 = np.ones(256)*yp[1]

X1, Y1 = np.meshgrid(x1, y1)
X2, Y1 = np.meshgrid(x2, y1)

gradient1 = (X1*Y1)
gradient2 = (X2*Y1)

## plot the blackgroun with diverging colormap
plt.imshow(gradient1, cmap=cm1, extent=(xp[0], div_point_x, yp[0], yp[1]),aspect='auto', origin='lower',alpha=0.7)
plt.imshow(gradient2, cmap=cm2, extent=(div_point_x, xp[1], yp[0], yp[1]),aspect='auto', origin='lower',alpha=0.7)

plt.xlim(xp)
plt.ylim(yp)

字符串

相关问题