我已经阅读了adjustText
包在避免标签重叠方面的效率,我想参考prince
创建的下图:
这里是创建图像的代码:
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
应用于此图形?
首先,通过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]
结构XCOLS
,YCOLS
,XROWS
,YROWS
是字典,其值是浮点数(坐标)。让我们将两个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')
结果是:
注意,在没有adjust_text
的情况下图像生成是瞬时的,而在adjust_text
的情况下花费了大约40秒。