簡體   English   中英

使用Matplotlib使用設置數字的個性化色彩圖

[英]Personalised colourmap plot using set numbers using matplotlib

我有一個看起來像的數據(示例)

x y  d
0 0 -2
1 0  0
0 1  1 
1 1  3

我想將其轉換為如下圖所示的coloumap圖:

在此處輸入圖片說明

其中x和y在表中,顏色由“ d”給出。 但是,我希望為每個數字指定預定的顏色,例如:

-2 - orange
 0 - blue
 1 - red
 3 - yellow

這些顏色不一定是這些顏色,但是我需要為顏色指定數字,並且數字不是按順序或順序排列的,它們只是五個或六個隨機數的集合,它們在整個數組中重復出現。

任何想法,我都沒有代碼,因為我不知道從哪里開始。 但是,我查看了以下示例:

Matplotlib python更改顏色圖中的單一顏色

但是,它們僅顯示如何定義顏色,而不顯示如何將這些顏色鏈接到特定值。

事實證明,這比我想象的要難,所以也許有人可以更輕松地做到這一點。

由於我們需要創建數據的圖像,因此我們將它們存儲在2D數組中。 然后,我們可以將數據映射到0 .. number of different data values的整數0 .. number of different data values並為每個顏色分配一種顏色。 原因是我們希望最終的色彩圖等距分布。 所以

-2 >整數0 >顏色orange
0 >整數1 >顏色blue ,依此類推。

由於整數間隔良好,我們可以在新創建的整數值的圖像上使用ListedColormap

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors

# define the image as a 2D array
d = np.array([[-2,0],[1,3]])

# create a sorted list of all unique values from d
ticks = np.unique(d.flatten()).tolist()
# create a new array of same shape as d
# we will later use this to store values from 0 to number of unique values
dc = np.zeros(d.shape)
#fill the array dc
for i in range(d.shape[0]):
    for j in range(d.shape[1]):
        dc[i,j] = ticks.index(d[i,j])

# now we need n (= number of unique values) different colors        
colors= ["orange", "blue", "red", "yellow"]
# and put them to a listed colormap
colormap =  matplotlib.colors.ListedColormap(colors)


plt.figure(figsize=(5,3))
#plot the newly created array, shift the colorlimits, 
# such that later the ticks are in the middle
im = plt.imshow(dc, cmap=colormap, interpolation="none", vmin=-0.5, vmax=len(colors)-0.5)
# create a colorbar with n different ticks
cbar = plt.colorbar(im, ticks=range(len(colors)) )
#set the ticklabels to the unique values from d
cbar.ax.set_yticklabels(ticks)
#set nice tickmarks on image
plt.gca().set_xticks(range(d.shape[1]))
plt.gca().set_yticks(range(d.shape[0]))

plt.show()

在此處輸入圖片說明


由於可能無法直觀地弄清楚如何以imshow繪制所需形狀的數組d ,即2D數組,因此有兩種轉換輸入數據列的方法:

import numpy as np

x = np.array([0,1,0,1])
y  = np.array([ 0,0,1,1])
d_original = np.array([-2,0,1,3])

#### Method 1 ####
# Intuitive method. 
# Assumption: 
#    * Indexing in x and y start at 0 
#    * every index pair occurs exactly once.
# Create an empty array of shape (n+1,m+1) 
#   where n is the maximum index in y and
#         m is the maximum index in x
d = np.zeros((y.max()+1 , x.max()+1), dtype=np.int) 
for k in range(len(d_original)) :
    d[y[k],x[k]] = d_original[k]  
print d

#### Method 2 ####
# Fast method
# Additional assumption: 
#  indizes in x and y are ordered exactly such
#  that y is sorted ascendingly first, 
#  and for each index in y, x is sorted. 
# In this case the original d array can bes simply reshaped
d2 = d_original.reshape((y.max()+1 , x.max()+1))
print d2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM