Spaces:
Sleeping
Sleeping
Commit ·
0058591
1
Parent(s): bb1f78e
Add classification matrix heatmap visualization
Browse filesNew dropdown to switch between:
- Category Distribution: bar chart showing percentage per category
- Classification Matrix: binary heatmap showing each response's classifications
(green = present, black = not present)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
632 unmodified lines633634635636637638943 unmodified lines158215831584158515861587158815891590159115921593159415951596632 unmodified linesreturn sanitized[:40]def create_distribution_chart(result_df, categories, classify_mode="Single Model", models_list=None):"""Create a bar chart showing category distribution.943 unmodified linesif st.session_state.results:results = st.session_state.results# Distribution chartfig = create_distribution_chart(results['df'],results['categories'],classify_mode=results.get('classify_mode', 'Single Model'),models_list=results.get('models_list', []))st.pyplot(fig)st.caption("Note: Categories are not mutually exclusive—each item can belong to multiple categories.")# Results dataframe (hide technical columns from display)display_df = results['df'].copy()632 unmodified lines633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723943 unmodified lines16671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698632 unmodified linesreturn sanitized[:40]def create_classification_heatmap(result_df, categories, classify_mode="Single Model", models_list=None):"""Create a binary heatmap showing classification for each row.Args:result_df: DataFrame with classification resultscategories: List of category namesclassify_mode: "Single Model", "Model Comparison", or "Ensemble"models_list: List of model names (for multi-model modes)"""import numpy as nptotal_rows = len(result_df)if total_rows == 0:fig, ax = plt.subplots(figsize=(10, 4))ax.text(0.5, 0.5, 'No data to display', ha='center', va='center', fontsize=14)ax.axis('off')return fig# Build the binary matrix based on classify_modeif classify_mode == "Ensemble":# Use consensus columnscol_names = [f"category_{i}_consensus" for i in range(1, len(categories) + 1)]elif classify_mode == "Model Comparison" and models_list:# Use first model's columns for the heatmapsanitized = sanitize_model_name(models_list[0])col_names = [f"category_{i}_{sanitized}" for i in range(1, len(categories) + 1)]else:# Single modelcol_names = [f"category_{i}" for i in range(1, len(categories) + 1)]# Extract the binary matrixmatrix_data = []for col in col_names:if col in result_df.columns:matrix_data.append(result_df[col].astype(int).values)else:matrix_data.append(np.zeros(total_rows, dtype=int))matrix = np.array(matrix_data).T # Rows = responses, Cols = categories# Create figure with appropriate sizingfig_height = max(4, min(20, total_rows * 0.15))fig_width = max(8, len(categories) * 0.8)fig, ax = plt.subplots(figsize=(fig_width, fig_height))# Create custom colormap: black (0) and green (1)from matplotlib.colors import ListedColormapcmap = ListedColormap(['#1a1a1a', '#22c55e'])# Plot heatmapim = ax.imshow(matrix, aspect='auto', cmap=cmap, vmin=0, vmax=1)# Set labelsax.set_xticks(range(len(categories)))ax.set_xticklabels(categories, rotation=45, ha='right', fontsize=9)ax.set_xlabel('Categories', fontsize=11)ax.set_ylabel('Responses', fontsize=11)# Limit y-axis labels for large datasetsif total_rows > 50:# Show fewer tick markstick_step = max(1, total_rows // 20)ax.set_yticks(range(0, total_rows, tick_step))else:ax.set_yticks(range(total_rows))title = 'Classification Matrix'if classify_mode == "Ensemble":title += ' (Ensemble Consensus)'elif classify_mode == "Model Comparison":title += f' ({models_list[0].split("/")[-1].split(":")[0][:20]})'ax.set_title(title, fontsize=14, fontweight='bold')# Add legendfrom matplotlib.patches import Patchlegend_elements = [Patch(facecolor='#1a1a1a', edgecolor='white', label='Not Present'),Patch(facecolor='#22c55e', edgecolor='white', label='Present')]ax.legend(handles=legend_elements, loc='upper right', bbox_to_anchor=(1.15, 1))plt.tight_layout()return figdef create_distribution_chart(result_df, categories, classify_mode="Single Model", models_list=None):"""Create a bar chart showing category distribution.943 unmodified linesif st.session_state.results:results = st.session_state.results# Visualization selectorviz_type = st.selectbox("Visualization",options=["Category Distribution", "Classification Matrix"],key="viz_type",help="Distribution shows category percentages. Matrix shows each response's classifications.")if viz_type == "Category Distribution":fig = create_distribution_chart(results['df'],results['categories'],classify_mode=results.get('classify_mode', 'Single Model'),models_list=results.get('models_list', []))st.pyplot(fig)st.caption("Note: Categories are not mutually exclusive—each item can belong to multiple categories.")else:fig = create_classification_heatmap(results['df'],results['categories'],classify_mode=results.get('classify_mode', 'Single Model'),models_list=results.get('models_list', []))st.pyplot(fig)st.caption("Green = category present, Black = not present. Each row is one response.")# Results dataframe (hide technical columns from display)display_df = results['df'].copy()
app.py+110-8