python - Matplotlib 颜色图显示不正确的颜色
问题描述
我需要制作一个从红色到白色的 256 种颜色的颜色图,并在 Python 中显示红色通道,但看起来这件事做错了,我不明白为什么。这是我的代码:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# How to create an array filled with zeros
img = np.zeros([256,256])
colormap1 = np.zeros([256,1])
#image:
for i in range(256):
img[:,i] = i #on all columns I have the same value
#to go from red to white we'll have: [1,0,0]...,[1,0.5,0.5],..[1,1,1]
for i in range(128):
colormap1[i,1] = i/127
#display the thing:
colormap1 = mpl.colors.ListedColormap(colormap1)
plt.figure(), plt.imshow(img, cmap = colormap1)
解决方案
你可以这样回答:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# How to create an array filled with zeros
img = np.zeros([256,256])
colormap = np.zeros([256,3])
#image:
for i in range(256):
img[:,i] = i #on all columns I have the same value
#color map:
for i in range(256):
colormap[i,0] = 1
colormap[i,1] = (i+1)/256
colormap[i,2] = (i+1)/256
#display the thing:
colormap = mpl.colors.ListedColormap(colormap)
plt.figure(), plt.imshow(img, cmap = colormap)
几乎就像你在这里所做的那样Colormap 它不是由正确的颜色组成的。您只需要编写代码的第二部分(从红色到白色)并在 256 步而不是 128 步中完成。
推荐阅读
- scroll - 有没有办法在仪表板中制作可滚动的部分?
- json - 状态消息:无法对嵌套资源执行请求的操作。未找到父资源“VMName”。(代码:ParentResourceNotFound)
- python - 我如何使用这个 for 循环到这个 webscraping stock 模块?
- python - 如何根据一组多对模式中两个模式的共现来修剪字符串?
- sql - LIMIT 不包含变量
- python - 有没有办法检查两个对象列表是否仅包含 Python 中相同类型的对象?
- reactjs - 在聚合物中反应 JSX?这是可能的?
- python - 如何使用作为列表的数据框值
- saml - 使用 GSuite Google Workspace 配置 SCIM 用户配置
- python - 如果不存在,如何使用 python 创建 postgres 用户/角色