使用adjustText避免标签与Python王子对应分析重叠

问题描述 投票:0回答:1

我已经阅读了adjustText包在避免标签重叠方面的效率,我想参考prince创建的下图:

enter image description here

这里是创建图像的代码:

import pandas as pd
import prince
from adjustText import adjust_text

pd.set_option('display.float_format', lambda x: '{:.6f}'.format(x))
X=pd.DataFrame(data=[ ... my data ... ],
columns=pd.Series([ ... my data ... ]),
index=pd.Series([ ... my data ...]),
)

ca = prince.CA(n_components=2,n_iter=3,copy=True,check_input=True,engine='auto',random_state=42)
ca = ca.fit(X)
ca.row_coordinates(X)
ca.column_coordinates(X)
ax = ca.plot_coordinates(X=X,ax=None,figsize=(6, 6),x_component=0,y_component=1,show_row_labels=True,show_col_labels=True)

ax.get_figure().savefig('figure.png')

在我发现的adjustText的所有示例中,始终可以直接访问标签的坐标。在这种情况下,如何访问标签的坐标?如何将adjust_text应用于此图形?

python pandas label overlap correspondence-analysis
1个回答
0
投票

首先,通过plot_coordinates()禁用标签显示:

ax = ca.plot_coordinates(X=X,ax=None,figsize=(6, 6),x_component=0,y_component=1,show_row_labels=False,show_col_labels=False)

然后,提取列和行的坐标:

COLS=ca.column_coordinates(X).to_dict()
XCOLS=COLS[0]
YCOLS=COLS[1]
ROWS=ca.row_coordinates(X).to_dict()
XROWS=ROWS[0]
YROWS=ROWS[1]

结构XCOLSYCOLSXROWSYROWS是字典,其值是浮点数(坐标)。让我们将两个x轴字典合并到一个x轴字典中,我将把XGLOBAL(与y轴字典相同)合并到YGLOBAL中:

XGLOBAL={ k : XCOLS.get(k,0)+XROWS.get(k,0) for k in set(XCOLS) | set(XROWS) }
YGLOBAL={ k : YCOLS.get(k,0)+YROWS.get(k,0) for k in set(YCOLS) | set(YROWS) }

现在我只需按照文档中的说明使用adjust_text()

fig = ax.get_figure()
texts=[plt.text(XGLOBAL[x],YGLOBAL[x],x,fontsize=7) for x in XGLOBAL.keys()]
adjust_text(texts,arrowprops=dict(arrowstyle='-', color='red'))
fig.savefig('newfigure.png')

结果是:

enter image description here

注意,在没有adjust_text的情况下图像生成是瞬时的,而在adjust_text的情况下花费了大约40秒。

© www.soinside.com 2019 - 2024. All rights reserved.