如何将Seaborn箱线图下方表格的内容垂直居中对齐
问题:Seaborn箱线图下方表格内容垂直居中对齐的解决方法
我使用以下代码创建了Seaborn箱线图,并在图下方添加了汇总统计表:
#Packages import pandas as pd from pandas.plotting import table import matplotlib.pyplot as plt import seaborn as sns #Directories export_directory = "C:/Users/xyz/Downloads/" #Sample Data df = pd.DataFrame({'entity': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 'score': [33, 34, 35, 35, 36, 49, 44, 46, 45, 48, 62, 60, 62, 63, 61], 'category': ['sm', 'sm', 'sm', 'sm', 'sm', 'md', 'md', 'md', 'md', 'md', 'lg', 'lg', 'lg', 'lg', 'lg']}) #Create seaborn boxplot fig1, ax1 = plt.subplots() sns.boxplot(y=df['score'], x=df['category']) #Create pivot table for count & median values, then transpose the table so it aligns with x axis later pivotdf = df.pivot_table(index='category', values='score', aggfunc={'count','median'}).T #Flip column order to align with x axis in plot pivotdf = pivotdf[pivotdf.columns[::-1]] #Create a matplotlib table from the pivotdf pivottable = table(ax1, pivotdf, cellLoc='center', loc='bottom') #Add the matplotlib table beneath the boxplot ax1.add_table(pivottable) #Remove x axis label & ticks since they overlap with the pivot table ax1.set(xlabel=None) ax1.set_xticks([]) #Save the figure fig1.savefig(export_directory+'boxplotfig.png', bbox_inches='tight')

运行后我发现表格内容已水平居中,但垂直对齐方式为顶部,内容紧贴单元格上方显得拥挤。我尝试使用以下代码:
ax1.table1.set_text_props(va='center')
但未解决问题,请问如何将表格内容垂直居中对齐?
解决方法
问题出在你引用了不存在的ax1.table1对象,正确的操作对象是你创建的pivottable。只需修改代码,对pivottable设置文本垂直居中属性即可,还可以调整单元格行高优化显示效果:
修改后的关键代码
在创建pivottable之后,添加以下代码:
# 设置表格文本垂直居中 pivottable.set_text_props(va='center') # 调整表格行高,让垂直居中效果更自然(可选) for cell in pivottable.get_celld().values(): cell.set_height(0.08) # 可根据需求调整高度数值
完整修改后的代码
#Packages import pandas as pd from pandas.plotting import table import matplotlib.pyplot as plt import seaborn as sns #Directories export_directory = "C:/Users/xyz/Downloads/" #Sample Data df = pd.DataFrame({'entity': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 'score': [33, 34, 35, 35, 36, 49, 44, 46, 45, 48, 62, 60, 62, 63, 61], 'category': ['sm', 'sm', 'sm', 'sm', 'sm', 'md', 'md', 'md', 'md', 'md', 'lg', 'lg', 'lg', 'lg', 'lg']}) #Create seaborn boxplot fig1, ax1 = plt.subplots() sns.boxplot(y=df['score'], x=df['category']) #Create pivot table for count & median values, then transpose the table so it aligns with x axis later pivotdf = df.pivot_table(index='category', values='score', aggfunc={'count','median'}).T #Flip column order to align with x axis in plot pivotdf = pivotdf[pivotdf.columns[::-1]] #Create a matplotlib table from the pivotdf pivottable = table(ax1, pivotdf, cellLoc='center', loc='bottom') # 设置表格文本垂直居中 pivottable.set_text_props(va='center') # 调整表格行高 for cell in pivottable.get_celld().values(): cell.set_height(0.08) #Add the matplotlib table beneath the boxplot ax1.add_table(pivottable) #Remove x axis label & ticks since they overlap with the pivot table ax1.set(xlabel=None) ax1.set_xticks([]) #Save the figure fig1.savefig(export_directory+'boxplotfig.png', bbox_inches='tight')
这样修改后,表格内的文本就会垂直居中显示,调整行高还能避免内容拥挤的问题。
内容的提问来源于stack exchange,提问作者dean
相关产品推荐
相关产品推荐

