假設要保存爲彩色圖,後來轉換爲灰度,你可以做到以下幾點:
從您最喜愛的顏色表定義的顏色列表。 [這裏還值得注意的是,使用新的4色配色(自matplotlib 1.5:viridis,magma,plasma,inferno開始可用)意味着圖像轉換爲灰度時顏色仍然可以區分]。
colors = plt.cm.plasma(np.linspace(0., 1., 5))
然後,我們可以定義一個函數的那些顏色轉換爲它們的等效灰度值:
rgb2gray = lambda rgb: np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
如果該值大於0.5時,顏色是淺色,因此我們可以使用黑色文本,否則,將文本更改爲深色。我們可以使用下面的列表中理解保存到列表中的那些文字顏色:
textcol = ['k' if rgb2gray(color) > 0.5 else 'w' for color in colors ]
當您繪製的餅圖,使用colors=colors
kwarg使用先前定義的顏色。 matplotlib
從ax.pie
返回三項內容:構成餅圖,文本標籤和autopct
標籤的補丁。後者是我們想要修改的。
p, t, at = ax1.pie(train_sentences_b, autopct='%1.1f%%',
shadow=True, startangle=90, colors=colors)
讓我們定義循環功能通過文本標籤,並設置其顏色取決於我們做早期的名單上:
def fix_colors(textlabels, textcolors):
for text, color in zip(textlabels, textcolors):
text.set_color(color)
然後,我們每一個餅圖使用繪製之後,調用此:
fix_colors(at, textcol)
把所有在一起,在您的腳本(我加了一些電子XTRA數據獲取餅圖上的所有5名作):
import matplotlib.pyplot as plt
from matplotlib.pyplot import savefig
import numpy as np
import matplotlib.gridspec as gridspec
colors = plt.cm.plasma(np.linspace(0., 1., 5))
rgb2gray = lambda rgb: np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
textcol = ['k' if rgb2gray(color) > 0.5 else 'w' for color in colors ]
def fix_colors(textlabels, textcolors):
for text, color in zip(textlabels, textcolors):
text.set_color(color)
plt.clf()
plt.cla()
plt.close()
labels_b = ["Very Negative", "Negative", "Neutral", "Positive", "Very Positive"]
dev_sentences_b = [428, 444, 430, 500, 320]
test_sentences_b = [912, 909, 890, 900, 900]
train_sentences_b = [3310, 3610, 3200, 3500, 3321]
gs = gridspec.GridSpec(2, 2)
ax1= plt.subplot(gs[0, 0])
p, t, at = ax1.pie(train_sentences_b, autopct='%1.1f%%',
shadow=True, startangle=90, colors=colors)
fix_colors(at, textcol)
ax1.axis('equal')
ax1.set_title("Train")
ax2= plt.subplot(gs[0, 1])
p, t, at = ax2.pie(dev_sentences_b, autopct='%1.1f%%',
shadow=True, startangle=90, colors=colors)
ax2.axis('equal')
ax2.set_title("Dev")
fix_colors(at, textcol)
ax3 = plt.subplot(gs[1, 1])
p, t, at = ax3.pie(test_sentences_b, autopct='%1.1f%%',
shadow=True, startangle=90, colors=colors)
ax3.axis('equal')
ax3.set_title("Test")
fix_colors(at, textcol)
ax3.legend(labels=labels_b, bbox_to_anchor=(-1,1), loc="upper left")
plt.savefig('sstbinary', format='pdf')
這給下面的圖片:
並轉換爲灰度後:
使用餅圖中數字的白色字體可能是一個解決方案。看看這裏:https://stackoverflow.com/questions/27898830/python-how-to-change-autopct-text-color-to-be-white-in-a-pie-chart和這裏:https:/ /matplotlib.org/examples/pylab_examples/pie_demo2.html –