matplotlib分面子图中如何为饼图添加黑色矩形外边框
问题说明
使用matplotlib绘制2行2列分面图时,3个堆叠柱状图子图默认带有黑色矩形外边框,但首个饼图子图无此外框,需要统一子图样式,让饼图也显示相同的黑色外框。
附问题复现代码:
import pandas as pd import numpy as np pd.set_option('max_columns', None) import matplotlib.pyplot as plt import matplotlib as mpl # 数据 data = { 'type_sale': ['g_1','g_2','g_3','g_4','g_5','g_6','g_7','g_8','g_9','g_10'], 'open':[70,20,24,150,80,90,60,90,20,20], 'closed':[30,14,20,10,20,40,10,10,10,10], } df = pd.DataFrame(data, columns = ['type_sale','open','closed']) data1 = { 'type_sale': [ 'open','closed'], 'structure':[70,30], } df1 = pd.DataFrame(data1, columns = ['type_sale','structure']) # 绘图 labels = ['open','closed'] fig, axs = plt.subplots(2,2, figsize=(10,8)) plt.subplots_adjust(wspace=0.2, hspace=0.6) df1.plot(x='type_sale', y='structure',labels=labels,autopct='%1.1f%%',kind='pie', title='Stacked Bar Graph by dataframe',ax=axs[0,0]) df.plot(x='type_sale', kind='bar', stacked=True, title='Stacked Bar Graph by dataframe', ax=axs[0,1]) df.plot(x='type_sale', kind='bar', stacked=True, title='Stacked Bar Graph by dataframe',ax=axs[1,0]) df.plot(x='type_sale', kind='bar', stacked=True,title='Stacked Bar Graph by dataframe', ax=axs[1,1]) plt.suptitle(t='Stacked Bar Graph by dataframe', fontsize=16) plt.show()
效果参考:
解决方法
matplotlib绘制饼图时默认会隐藏坐标轴外框,在饼图绘制完成后,为对应子图添加如下代码即可开启外框显示,边框默认样式和其余柱状图子图完全一致:
axs[0,0].set_frame_on(True)
修改后完整代码
import pandas as pd import numpy as np pd.set_option('max_columns', None) import matplotlib.pyplot as plt import matplotlib as mpl # 数据 data = { 'type_sale': ['g_1','g_2','g_3','g_4','g_5','g_6','g_7','g_8','g_9','g_10'], 'open':[70,20,24,150,80,90,60,90,20,20], 'closed':[30,14,20,10,20,40,10,10,10,10], } df = pd.DataFrame(data, columns = ['type_sale','open','closed']) data1 = { 'type_sale': [ 'open','closed'], 'structure':[70,30], } df1 = pd.DataFrame(data1, columns = ['type_sale','structure']) # 绘图 labels = ['open','closed'] fig, axs = plt.subplots(2,2, figsize=(10,8)) plt.subplots_adjust(wspace=0.2, hspace=0.6) df1.plot(x='type_sale', y='structure',labels=labels,autopct='%1.1f%%',kind='pie', title='Stacked Bar Graph by dataframe',ax=axs[0,0]) # 开启饼图子图外框 axs[0,0].set_frame_on(True) df.plot(x='type_sale', kind='bar', stacked=True, title='Stacked Bar Graph by dataframe', ax=axs[0,1]) df.plot(x='type_sale', kind='bar', stacked=True, title='Stacked Bar Graph by dataframe',ax=axs[1,0]) df.plot(x='type_sale', kind='bar', stacked=True,title='Stacked Bar Graph by dataframe', ax=axs[1,1]) plt.suptitle(t='Stacked Bar Graph by dataframe', fontsize=16) plt.show()
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

