2017-10-10 130 views
2

繼pylab_examples,我在matplotlib創建了一個簡單的2×細胞表。如何分配在Matplotlib表特定顏色的特定細胞?

代碼:

# Prepare table 
columns = ('A', 'B', 'C', 'D', 'E') 
rows = ["A", "B"] 
cell_text = [["1", "1","1","1","1"], ["2","2","2","2","2"]] 
# Add a table at the bottom of the axes 
ax[4].axis('tight') 
ax[4].axis('off') 
the_table = ax[4].table(cellText=cell_text,colLabels=columns,loc='center') 

現在,我要的顏色單元格A1與color = "#56b5fd"和單元格A2與color = "#1ac3f5"。所有其他細胞應保持白色。 Matplotlib的table_demo.py以及this例如只告訴我如何應用彩色地圖依賴於細胞中的值預先定義的顏色。

如何分配在Matplotlib生成表的具體顏色以特定細胞?

回答

3

上色在表格單元格的背景最簡單的方法是使用cellColours參數。您可以提供與數據形狀相同的列表或陣列列表。

import matplotlib.pyplot as plt 
# Prepare table 
columns = ('A', 'B', 'C', 'D', 'E') 
rows = ["A", "B"] 
cell_text = [["1", "1","1","1","1"], ["2","2","2","2","2"]] 
# Add a table at the bottom of the axes 
colors = [["#56b5fd","w","w","w","w"],[ "#1ac3f5","w","w","w","w"]] 

fig, ax = plt.subplots() 
ax.axis('tight') 
ax.axis('off') 
the_table = ax.table(cellText=cell_text,cellColours=colors, 
        colLabels=columns,loc='center') 

plt.show() 

enter image description here

替代地,可以設置一個特定小區的facecolor作爲

the_table._cells[(1, 0)].set_facecolor("#56b5fd") 
the_table._cells[(2, 0)].set_facecolor("#1ac3f5") 

在相同的輸出如上所得到的。