ListedColormap用于在python中的matplotlib.pyplot.grid中标识网格正方形

时间:2019-03-05 23:56:03

标签: python numpy matplotlib

如何在使用python中的matplotlib.pyplot创建的网格中引用或标识特定的网格正方形?我已经使用ListedColorMap做到了,但是我不明白如何将网格正方形的颜色更改为不同的颜色,以及ListedColormaps如何工作?

这是我的代码:

import matplotlib as mpl
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import itertools


N = 15
# making an empty data set
data = np.ones((N, N)) 


fig = plt.figure()              # creates the figure
ax = fig.gca() 


# fill in some sample data
data[6] = 1


# make color map
my_cmap = mpl.colors.ListedColormap(['g', 'b'])


ax.set_xticks(np.arange(-10, 0, 1))
ax.set_yticks(np.arange(-10, 0, 1))


for t in range(N + 1):
   ax.axhline(t, lw=2, color='k', zorder=5)
   ax.axvline(t, lw=2, color='k', zorder=5)

# draw the boxes
ax.imshow(data, interpolation='none', cmap=my_cmap, extent=[0, N, 0, N], 
zorder=0)
# turn off the axis labels
ax.axis('on')

plt.show()

1 个答案:

答案 0 :(得分:0)

要为网格上的某些特定正方形设置颜色,首先需要确保这些位置的data与其他位置不同。例如,如果您想要第一行的前两列第二行的前两列作为颜色,则可以执行以下操作:

# Your data variable starts of having 1's at every location.
# To be able to see different colors, change the data
# at those locations. Here we set the data to 2. It could be
# any number different from 1.
data[0][0] = 2
data[0][1] = 2
data[1][0] = 2
data[1][1] = 2

以上内容可帮助您更改网格上特定正方形的颜色。

如果要指定网格显示的颜色,则必须在matplotlib.colors.ListedColormap(colors, name='from_list', N=None) colors 参数中指定它们。

# In this case, 'w' or white will be used for all the 1's in data.
# 'b' or blue will be used for all the 2's and 'r' or red for all the 3's.
# If you want to add new data, you can make it use new colors by adding
# more colors to the colors list.
# If you add new data but not new colors, the last color will be selected
# for the new data. 
my_cmap = mpl.colors.ListedColormap(['w', 'b', 'r'])

参考:ListedColorMap

参考:colors - Matplotlib