如何在Python中为UpSet图添加标题并修改绘图样式?
UpSet图标题添加及数据适配解决方案
环境与数据说明
已安装并导入依赖库:
!pip install upsetplot import numpy as np import pandas as pd import matplotlib.pyplot as plt import upsetplot from upsetplot import generate_data, plot from upsetplot import UpSet from upsetplot import from_contents
版本信息:
- Python 3.8.16
- Numpy version: 1.21.6
- Pandas version: 1.3.5
- matplotlib version: 3.2.2
- upsetplot 0.8.0
定义绘图颜色:
plot_colour = "#4F84B9"
目标数据:
df = pd.DataFrame({'File':['File_1', 'File_2', 'File_3'], 'A':[1,1,0], 'B':[0,1,1], 'C':[1,0,1]})
原代码中,将数据转换为UpSet格式后绘图时出现错误:
files_labelled_A = set(df.loc[df["A"]==1, "File"]) files_labelled_B = set(df.loc[df["B"]==1, "File"]) files_labelled_C = set(df.loc[df["C"]==1, "File"]) contents = {'A': files_labelled_A, 'B': files_labelled_B, 'C': files_labelled_C} # 原绘图代码(存在变量名冲突问题) # plt = UpSet(from_contents(contents), subset_size='count', facecolor=plot_colour).plot() # plt.title('my title here') # 报错:AttributeError: 'dict' object has no attribute 'title'
解决方案1:修改现有方法添加Matplotlib样式(含标题)
问题根源是变量名冲突:将UpSet.plot()返回的字典对象赋值给了plt,覆盖了导入的matplotlib.pyplot as plt。修正变量名后,直接使用matplotlib的API修改样式:
# 1. 转换数据格式 files_labelled_A = set(df.loc[df["A"]==1, "File"]) files_labelled_B = set(df.loc[df["B"]==1, "File"]) files_labelled_C = set(df.loc[df["C"]==1, "File"]) contents = {'A': files_labelled_A, 'B': files_labelled_B, 'C': files_labelled_C} # 2. 绘图,避免覆盖matplotlib的plt变量 upset_axes = UpSet(from_contents(contents), subset_size='count', facecolor=plot_colour).plot() # 3. 添加标题及其他Matplotlib样式修改 plt.title('UpSet图:文件标签交集统计', y=1.05) # y参数调整标题位置,避免被图遮挡 plt.xlabel('标签组合') plt.ylabel('文件数量') # 显示图形 plt.show()
解决方案2:将数据适配为generate_counts()格式绘图
先将数据转换为带多索引的计数Series(与generate_counts()生成的数据格式一致),再用upsetplot.plot()绘图:
# 1. 从原DataFrame生成交集计数 # 先将每行转换为(A,B,C)的布尔元组,统计每个组合的出现次数 df['combination'] = df.apply(lambda row: (row['A']==1, row['B']==1, row['C']==1), axis=1) counts = df['combination'].value_counts() # 为索引设置名称,匹配upsetplot要求 counts.index = pd.MultiIndex.from_tuples(counts.index, names=['A', 'B', 'C']) # 2. 用upsetplot.plot绘图 upsetplot.plot(counts, facecolor=plot_colour, subset_size='count') # 3. 添加标题及样式修改 plt.title('UpSet图:文件标签交集统计', y=1.05) plt.xlabel('标签组合') plt.ylabel('文件数量') # 显示图形 plt.show()
内容的提问来源于stack exchange,提问作者code_to_joy
相关产品推荐
相关产品推荐

