设置return_type='both'后,如何获取matplotlib箱线图并保存?
解决pandas boxplot return_type='both'后无法获取figure的问题
这个报错的原因很清晰:当你给boxplot()传入return_type='both'时,pandas返回的不是单个Axes对象,而是一个pandas Series——其中每个元素都是元组(坐标轴对象Axes, 箱线图元素字典)。你直接调用bp.figure自然会报错,因为Series本身没有figure属性。
要解决这个问题,核心是从返回的Series里提取出Axes对象,再通过它来操作figure。这里有两种常用的处理方式:
方式一:遍历Series时保存Axes对象
遍历修改箱线图样式的同时,把坐标轴对象存下来,之后用它来调用figure的显示和保存方法:
import pandas as pd import os df = pd.DataFrame( columns=['mean_coverage', 'exon'], data={ 'mean_coverage': [102, 578, 75, 180], 'exon': [1, 1, 2, 2] } ) bp = df.boxplot( column='mean_coverage', by='exon', patch_artist=True, return_type='both' ) # 初始化坐标轴对象变量 plot_ax = None for row_key, (ax, row_elements) in bp.iteritems(): plot_ax = ax # 保存当前坐标轴 # 自定义箱线图样式 for box in row_elements['boxes']: box.set_facecolor('pink') # 通过保存的坐标轴获取figure并操作 if plot_ax is not None: plot_ax.figure.show() plot_ax.figure.savefig(os.path.join(self.output_path, 'ZRSR2.png'))
方式二:直接提取Series中的Axes对象
如果你的箱线图只有一个分组(或者只需要第一个绘图的坐标轴),可以直接通过Series的索引提取Axes对象:
bp = df.boxplot( column='mean_coverage', by='exon', patch_artist=True, return_type='both' ) # 提取第一个元素的坐标轴对象 plot_ax = bp.iloc[0][0] # 自定义样式 for row_key, (ax, row_elements) in bp.iteritems(): for box in row_elements['boxes']: box.set_facecolor('pink') # 操作figure plot_ax.figure.show() plot_ax.figure.savefig(os.path.join(self.output_path, 'ZRSR2.png'))
补充说明一下:当你不设置return_type或者设置为'axes'时,boxplot()直接返回单个Axes对象,所以bp.figure能正常工作;而return_type='both'是为了让你同时拿到坐标轴和箱线图的各个元素(比如箱子、须、中位数线等)来做精细化样式调整,代价就是返回结构变成了Series,需要多一步提取Axes的操作。
内容的提问来源于stack exchange,提问作者trouselife
相关产品推荐
相关产品推荐

