具有 3 种颜色的 Matplotlib 轮廓 [英] Matplotlib contourf with 3 colors

查看:47
本文介绍了具有 3 种颜色的 Matplotlib 轮廓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 3 种不同颜色制作等高线图.到目前为止,我的代码如下所示:

将 numpy 导入为 np导入matplotlib.pyplot作为pltxMin = 0xMax = 3xList = np.linspace(xMin,xMax,10)X1, X2 = np.meshgrid(xList, xList)Z = []#用Z做一些处理#Z现在包含0、0.5或1,例如Z = [0, 0, 0, 1, 1, 0.5, 1, 0.5...]Z = Z.reshape((len(X1),len(X2)))plt.contourf(X1, X2, Z,alpha=0.5)

现在,我想绘制每个轮廓,其中Z = 0为红色,Z = 0.5为绿色,Z = 1为蓝色.我不想在红色/绿色/蓝色之间有平滑的过渡,而只是一个颜色开关.我尝试了颜色和级别选项,但它并没有真正按预期工作.

等高线图是正确的方法吗?

解决方案

您可以使用colors选项控制等高线图的颜色,但您可能需要使用imshow来避免在各个级别之间进行插值.您可以使用

I would like to make a contour plot with 3 distinct colors. So far, my code looks like the following:

import numpy as np
import matplotlib.pyplot as plt

xMin = 0
xMax = 3
xList = np.linspace(xMin, xMax, 10)
X1, X2 = np.meshgrid(xList, xList)
Z = []
# do some processing with Z
# Z now contains 0, 0.5 or 1, e.g. Z = [0, 0, 0, 1, 1, 0.5, 1, 0.5...]
Z = Z.reshape((len(X1), len(X2)))
plt.contourf(X1, X2, Z,alpha=0.5)

Now I'd like to plot every contour where Z = 0 as red, Z = 0.5 as green and Z = 1 as blue. I do not want to have smooth transitions between red/green/blue, but just a color switch. I played around with the color and levels option, but it did not really work out as expected.

Is the contour plot the right way to go here?

解决方案

You can control the colors of a contour plot with the colors option but you might want to use imshow to avoid interpolation between the levels. You create a colormap for imshow with discrete levels using ListedColormap.

data = 0*np.ones((20,20))
data[5:15,5:15] = 0.5
data[7:12,8:16] = 1

# contourf plot
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.contourf(data, [0,0.4,0.9], colors = ['r','g','b']) 
ax1.set_aspect('equal')
ax1.set_title('contourf')

# imshow plot
ax2 = fig.add_subplot(2,2,2)
# define colr map
cmap = colors.ListedColormap(['r','g','b'])
bounds = [0, 0.4,0.6, 1.1]
norm = colors.BoundaryNorm(bounds, cmap.N)

ax2.imshow(data, interpolation = 'none', cmap=cmap, norm=norm)
ax2.set_title('imshow')

这篇关于具有 3 种颜色的 Matplotlib 轮廓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆