简体   繁体   English

如何 MatPlotLib plot 然后添加不同的轴?

[英]How to MatPlotLib plot and then add different axes?

I want to plot the solution of a PDE from (0, 0) to (10, 10).我想 plot 从 (0, 0) 到 (10, 10) 的 PDE 解。 The solution is given in a 20 by 20 matrix.解决方案以 20 x 20 矩阵形式给出。

Here is my code:这是我的代码:

plt.figure()
plt.title(f"Temperature at t = 100")
plt.xlabel("x")
plt.ylabel("y")

plt.pcolormesh(U[-1], cmap=plt.cm.jet)
plt.colorbar()

在此处输入图像描述

So I would like the same plot, but the axis should be from 0 to 10. Can I add a second axis that goes from 0 to 10 and then hide the current axis?所以我想要同样的 plot,但是轴应该是从 0 到 10。我可以添加第二个从 0 到 10 的轴,然后隐藏当前轴吗? Is it possible to achieve this without plt.subplots() because I would like to animate this figure ( animation.FuncAnimation(plt.figure(), animate, frames=range(0, max_iter)) , where animate is a function containing the code above)?是否可以在没有plt.subplots()的情况下实现这一点,因为我想为这个数字设置动画( animation.FuncAnimation(plt.figure(), animate, frames=range(0, max_iter)) ,其中 animate 是一个包含上面的代码)?

The solution U contains the color values and array shape information, but don't explicitly define the bounded x/y-values as you've pointed out.解决方案U包含颜色值和数组形状信息,但没有像您指出的那样明确定义有界 x/y 值。 To do this with pcolormesh , we just need to change the values according to the axes() class, as so (using a random dataset):要使用pcolormesh执行此操作,我们只需要根据axes() class 更改值,如下所示(使用随机数据集):

import numpy as np
import matplotlib.pyplot as plt

U = np.random.rand(20,20)
print(U.shape)

plt.figure()
ax=plt.axes()
plt.title(f"Temperature at t = 100")
plt.xlabel("x")
plt.ylabel("y")
plt.pcolormesh(U, cmap=plt.cm.jet)
x=y=np.linspace(0,10,11) # Define a min and max with regular spacing
ax.set_xticks(np.linspace(0,20,11)) # Ensure same number of x,y ticks
ax.set_yticks(np.linspace(0,20,11))
ax.set_xticklabels(x.astype(int)) # Change values according to the grid
ax.set_yticklabels(y.astype(int))
plt.colorbar()
plt.show()

彩色网格

Alternatively, we can explicitly define these using the extent=[<xmin>,<xmax>,<ymin>,<ymax>] option in imshow , as seen below:或者,我们可以使用imshow中的extent=[<xmin>,<xmax>,<ymin>,<ymax>]选项显式定义这些,如下所示:

import numpy as np
import matplotlib.pyplot as plt

U = np.random.rand(20,20)
print(U.shape) # Displays (20,20)

plt.figure()
plt.title(f"Temperature at t = 100")
plt.xlabel("x")
plt.ylabel("y")
plt.imshow(U, origin='lower', aspect='auto', extent = [0,10,0,10], cmap=plt.cm.jet)
plt.colorbar()
plt.show()

imshow 的输出

For further reading on which to use, pcolormesh or imshow , there is a good thread about it here: When to use imshow over pcolormesh?要进一步阅读使用哪个pcolormeshimshow ,这里有一个很好的主题: 何时使用 imshow 而不是 pcolormesh?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM