原始数据

绘图结果

代码
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
# 读取Excel文件
excel_path = 'result.xls'
# 1. 因子探测器(条形图)
factor_df = pd.read_excel(excel_path, sheet_name='Factor detector')
# 假设第一列为因子名,q列为q值,p-value列为p-value
factor_names = factor_df.iloc[:, 0]
q_values = factor_df['q']
# 兼容p-value为字符串或数值
p_values = factor_df['p-value'].astype(str)
plt.figure(figsize=(8, 6))
ax = sns.barplot(
y=factor_names,
x=q_values,
hue=factor_names,
palette='viridis',
legend=False
)
# 在柱子上标注q值,在柱子外侧标注***(p-value<0.01)
for i, (q, p) in enumerate(zip(q_values, p_values)):
bar = ax.patches[i]
# 柱子的右端x坐标
x = bar.get_width()
y = bar.get_y() + bar.get_height() / 2
# 在柱子中间标注q值
ax.text(x / 2, y, f'{q:.3f}', va='center', ha='center', color='white', fontsize=10, fontweight='bold')
# 如果p-value为<0.01,柱子外侧加***
if '<' in p or (p.replace('.', '', 1).isdigit() and float(p) < 0.01):
ax.text(x + max(q_values)*0.02, y, '***', va='center', ha='left', color='red', fontsize=14, fontweight='bold')
plt.xlabel('q')
plt.ylabel('Factor')
# plt.title('因子探测器')
# 添加图例说明
from matplotlib.lines import Line2D
legend_elements = [
Line2D([0], [0], color='#7B1FA2', lw=0, marker='s', markersize=10, markerfacecolor='#7B1FA2', label='q值'),
Line2D([0], [0], color='red', lw=0, marker='$***$', markersize=14, markerfacecolor='red', label='p<0.01')
]
ax.legend(handles=legend_elements, loc='lower right')
plt.tight_layout()
plt.savefig('FactorDtector.png')
plt.show()
plt.close()