我知道陰影顏色在繪制條形圖時遵循邊緣顏色,因此我繪制了兩次條形圖以分離陰影顏色和邊緣顏色。雖然這種方法適用于條形圖,但我不知道如何更改圖例中標記的邊緣顏色,以使圖例中的標記與條形圖一致。這是我的代碼和繪制的圖片。我想讓圖例中的標記也有像條一樣的黑色邊緣。
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
x_lable = ['3', '4', '5', '6', '7']
width = 0.3
data_1 = [2228, 2621, 3165, 3761, 3763]
data_2 = [3895, 5670, 7354, 8999, 10731]
data_3 = [4355, 6373, 8279, 10105, 12018]
xcoordinate = [1, 3, 5, 7, 9]
xcoordinate_1 = [xcoordinate[0] 0 * width, xcoordinate[1] 0 * width, xcoordinate[2] 0 * width, xcoordinate[3] 0 * width, xcoordinate[4] 0 * width]
xcoordinate_2 = [xcoordinate[0] 1 * width, xcoordinate[1] 1 * width, xcoordinate[2] 1 * width, xcoordinate[3] 1 * width, xcoordinate[4] 1 * width]
xcoordinate_3 = [xcoordinate[0] 2 * width, xcoordinate[1] 2 * width, xcoordinate[2] 2 * width, xcoordinate[3] 2 * width, xcoordinate[4] 2 * width]
xcoordinate_4 = [xcoordinate[0] 3 * width, xcoordinate[1] 3 * width, xcoordinate[2] 3 * width, xcoordinate[3] 3 * width, xcoordinate[4] 3 * width]
xcoordinate_5 = [xcoordinate[0] 4 * width, xcoordinate[1] 4 * width, xcoordinate[2] 4 * width, xcoordinate[3] 4 * width, xcoordinate[4] 4 * width]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.bar(xcoordinate_3, data_1, width=width, label='GGG', color='none', edgecolor='orange', hatch='\\\\\\')
ax1.bar(xcoordinate_4, data_2, width=width, label='SSS', color='none', edgecolor='blue', hatch='---')
ax1.bar(xcoordinate_5, data_3, width=width, label='KKK', color='none', edgecolor='orangered', hatch='///')
fmt='%.2f%%'
yticks = mtick.FormatStrFormatter(fmt)
ax1.set_ylabel('AAA')
ax1.set_xlabel('BBB')
plt.xticks([i 3 * width for i in xcoordinate], x_lable)
ax1.bar(xcoordinate_3, data_1, width=width, label='GGG', color='none', edgecolor='black')
ax1.bar(xcoordinate_4, data_2, width=width, label='SSS', color='none', edgecolor='black')
ax1.bar(xcoordinate_5, data_3, width=width, label='KKK', color='none', edgecolor='black')
handles1, labels1 = ax1.get_legend_handles_labels()
order = [0, 1, 2]
plt.legend([handles1[idx] for idx in order], [labels1[idx] for idx in order], loc=(2.5/10, 1.01), frameon=True, ncol=3, shadow=False, framealpha=1, labelspacing=1,handlelength=2).get_frame().set_edgecolor('black')
plt.show()

uj5u.com熱心網友回復:
只需添加第二個句柄:
order = [0, 1, 2]
plt.legend([handles1[idx] handles1[idx 3] for idx in order], [labels1[idx] for idx in order], loc=(2.5/10, 1.01), frameon=True, ncol=3, shadow=False, framealpha=1, labelspacing=1,handlelength=2).get_frame().set_edgecolor('black')
樣本輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440749.html
標籤:Python matplotlib 传奇 标记
