Seaborn柱状图设置width参数触发TypeError错误的排查求助
解决Seaborn barplot设置width参数触发TypeError的问题
问题描述
使用Seaborn绘制柱状图时,尝试设置width=0.5缩小柱体宽度,同时使用capsize参数添加误差棒,触发错误:TypeError: bar() got multiple values for argument 'width'。
错误原因
当barplot函数使用capsize参数时,内部会自动向matplotlib的bar方法传递width参数,此时手动传入的width会导致参数重复传递,引发错误。
解决方案
方案1:移除capsize参数直接设置width
如果不需要误差棒,直接去掉capsize参数即可正常设置width:
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd temp = [['STZ', 26376], ['Control', 31886], ['STZ', 28548], ['Control', 31000],['STZ', 29607], ['Control', 36659], ['Control', 32002] ] data = pd.DataFrame(temp, columns=['Image', 'Area (microns squared)']) plot_order = data.groupby('Image')['Area (microns squared)'].sum().sort_values(ascending=False).index.values color = sns.color_palette("Paired") sns.set(font_scale=2) sns.set_style(style='white') fig, ax = plt.subplots(figsize=(9,8)) ax = sns.barplot(x='Image',y='Area (microns squared)', data=data, palette=color, order=plot_order, width=0.5) plt.xlabel("Treatment") plt.ylabel("Area (microns squared)") plt.show()
方案2:保留capsize,手动调整柱体宽度
若需要保留误差棒,先完成绘图,再通过修改柱体补丁调整宽度:
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd temp = [['STZ', 26376], ['Control', 31886], ['STZ', 28548], ['Control', 31000],['STZ', 29607], ['Control', 36659], ['Control', 32002] ] data = pd.DataFrame(temp, columns=['Image', 'Area (microns squared)']) plot_order = data.groupby('Image')['Area (microns squared)'].sum().sort_values(ascending=False).index.values color = sns.color_palette("Paired") sns.set(font_scale=2) sns.set_style(style='white') fig, ax = plt.subplots(figsize=(9,8)) ax = sns.barplot(x='Image',y='Area (microns squared)', data=data, palette=color, order=plot_order, capsize=.1) # 调整柱体宽度为0.5,并保持居中 target_width = 0.5 for patch in ax.patches: current_width = patch.get_width() patch.set_width(target_width) # 计算偏移量,让柱体在x轴刻度上居中 patch.set_x(patch.get_x() + (current_width - target_width) / 2) plt.xlabel("Treatment") plt.ylabel("Area (microns squared)") plt.show()
方案3:升级Seaborn版本
旧版本Seaborn存在该参数冲突问题,升级到v0.11及以上版本后,可同时正常使用capsize和width参数,无需额外修改代码。
内容的提问来源于stack exchange,提问作者Adriana
相关产品推荐
相关产品推荐

