目標:給每個boxplot設定不同的顏色和屬性
官方文檔:https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.boxplot.html#matplotlib.axes.Axes.boxplot
切入點:可以看出是給在matplotlib.axes.Axes.boxplot
中的boxprops
進行參數(shù)設置靖诗,但是前提條件是要將patch_artist=True
稼病,將返回的結果按照版塊進行繪制,說明文檔:If False, produces boxes with the Line2D artist. Otherwise, boxes and drawn with Patch artists.。
想法:本來是想在boxprops
中的facecolor
中傳入一個color list旬昭,但沒成功,貌似在該參數(shù)下只能設置相同的顏色(需要求證)钻注,所以只能遍歷繪圖得到的patch片仿,挨個進行設置,主要代碼如下:
# 分組箱線圖陆淀,進行顏色設置
bp = axs.boxplot(y_group, showfliers=False, widths=[i *0.25 for i in pos],
labels=None, positions=pos, patch_artist=True)
[bp['boxes'][i].set(facecolor=color_list[i], alpha=0.7) for i in range(N)]
# 其中y_group是一個[[1, 2, 3], [1,2,3,4,5], [8,9]]格式的考余,即三個箱線圖的各自的分組數(shù)據(jù),pos是自定義的箱線圖的位置轧苫,color_list是每個顏色楚堤,N是箱線圖的數(shù)目。
# 當然也可以按照for循環(huán)進行挨個設置含懊,也可以列表表達式
其他一些參考資料
箱線圖樣式設置:https://stackoverflow.com/questions/28740234/face-pattern-for-boxes-in-boxplots
箱線圖透明色設置: https://stackoverflow.com/questions/61501795/set-boxplot-boxes-facecolor-transparency-in-python-matplotlib
箱線圖顏色填充:https://stackoverflow.com/questions/20289091/python-matplotlib-filled-boxplots
附上一個箱線圖的解釋