# def get_cos2_scores(pcomps):# ntrait, npcomp = pcomps.shape# x = np.zeros((ntrait, npcomp))# for i in range(ntrait):# cos2_trait = np.array([np.square(pcomps[i, pcidx]) for pcidx in range(npcomp)])# x[i, :] = cos2_trait / np.sum(cos2_trait)# return xdef compute_cos(factor):return (factor **2) / (np.sum(factor **2, axis =1).reshape((factor.shape[0], 1)))def stacked_barplot(ax, data, xlabels, colors, bar_width =1.0, alpha =1.0, showxlabels =False):''' Parameters ---------- data: dict() of scores. - <key> : items for the stacked bars (e.g. traits or components) - <value> : list of scores for the items. All dict entries must have the same length of <value> xlabels: label for each entry in the data <value> list. Must be of same length of data <value> colors: dict(<key>, <color>) corresponding to each data <key>. ''' indices = np.arange(len(xlabels)) bottom = np.zeros(len(xlabels))for item, weights in data.items(): ax.bar(indices, weights, bar_width, label = item, bottom = bottom, color = colors[item], alpha = alpha) bottom += weightsif showxlabels: ax.set_xticks(indices) ax.set_xticklabels(xlabels, rotation=90, ha='center') ax.tick_params(bottom =True, top =False, left =False, right =False, labelbottom =True, labeltop =False, labelleft =False, labelright =False)else: ax.tick_params(bottom =False, top =False, left =False, right =False, labelbottom =False, labeltop =False, labelleft =False, labelright =False)for side, border in ax.spines.items(): border.set_visible(False)returndef structure_plot(ax, pcomps, trait_labels, comp_colors, npcomp, showxlabels =False): cos2_scores = compute_cos(pcomps) cos2_plot_data = {f"{i+1}" : cos2_scores[:, i] for i inrange(npcomp) } stacked_barplot(ax, cos2_plot_data, trait_labels, comp_colors, alpha =0.8, showxlabels = showxlabels)return