首页 > 解决方案 > matplotlib 中不同颜色的流图给出 2 个 cmap

问题描述

流线图或流线图用于显示二维矢量场。我在 Python 中创建了一个具有不同颜色的流图,但cmap旁边有两个不同的颜色。使用的代码几乎与帮助文件相同,但我在第三个图上得到了多个 cmap。如何删除第二个 cmap?

下面是我使用的代码,后面是输出。

import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline
x,y = np.meshgrid(np.linspace(-5,5,20),np.linspace(-5,5,20))

xdot = y
ydot = -2*x - 3*y

# subplot2grid
fig = plt.figure(figsize=(18,10))
ax1 = plt.subplot2grid((2,2), (0, 0))
ax2 = plt.subplot2grid((2,2), (0, 1))
ax3 = plt.subplot2grid((2,2), (1, 0))
ax4 = plt.subplot2grid((2,2), (1, 1))

# Plot 1
Q = ax1.quiver(x, y, xdot, ydot, scale=500, angles='xy') # Quiver key
ax1.quiverkey(Q,-10,22.5,30,'5.1.8',coordinates='data',color='k')
ax1.set(xlabel='x', ylabel='y')
ax1.set_title('Quiver plot 6.1.1')

# Plot 2
strm  = ax2.streamplot(x, y, xdot, ydot, density=1, color='k', linewidth=2) # streamplot(X,Y,u,v)
fig.colorbar(strm.lines)
ax2.set(xlabel='x', ylabel='y')
ax2.set_title('Stream plot of 6.1.1')

# Plot 4
strm  = ax4.streamplot(x, y, xdot, ydot, density=1, color=xdot, linewidth=2, cmap='autumn') # streamplot(X,Y,u,v, density = 1)
fig.colorbar(strm.lines, ax=ax4)
ax4.set(xlabel='x', ylabel='y', title='Stream plot of 6.1.1 with varying color')

plt.show()

在此处输入图像描述

流图的帮助文件有一个示例,该示例可以解决此问题,并按预期工作。这是我用来绘制原始流图的。

  1. 流图
  2. 约束布局指南

概括

所以总结一下我的问题。如何删除侧面的两个颜色图?

任何帮助将不胜感激。

标签: pythonmatplotlibcolorsdata-visualizationsubplot

解决方案


您应该指定ax:ax2.streamplot

import numpy as np
import matplotlib.pyplot as plt

x,y = np.meshgrid(np.linspace(-5,5,20),np.linspace(-5,5,20))

xdot = y
ydot = -2*x - 3*y

# subplot2grid
fig = plt.figure(figsize=(18,10))
ax1 = plt.subplot2grid((2,2), (0, 0))
ax2 = plt.subplot2grid((2,2), (0, 1))
ax3 = plt.subplot2grid((2,2), (1, 0))
ax4 = plt.subplot2grid((2,2), (1, 1))

# Plot 1
Q = ax1.quiver(x, y, xdot, ydot, scale=500, angles='xy') # Quiver key
ax1.quiverkey(Q,-10,22.5,30,'5.1.8',coordinates='data',color='k')
ax1.set(xlabel='x', ylabel='y')
ax1.set_title('Quiver plot 6.1.1')

# Plot 2
strm  = ax2.streamplot(x, y, xdot, ydot, density=1, color='k', linewidth=2) # streamplot(X,Y,u,v)
fig.colorbar(strm.lines, ax = ax2) # <--- TO BE DELETED
ax2.set(xlabel='x', ylabel='y')
ax2.set_title('Stream plot of 6.1.1')

# Plot 4
strm  = ax4.streamplot(x, y, xdot, ydot, density=1, color=xdot, linewidth=2, cmap='autumn') # streamplot(X,Y,u,v, density = 1)
fig.colorbar(strm.lines, ax=ax4)
ax4.set(xlabel='x', ylabel='y', title='Stream plot of 6.1.1 with varying color')

plt.show()

在此处输入图像描述

或者,您可以删除上面的代码行以删除不需要的颜色条:

在此处输入图像描述


推荐阅读