chrissoria Claude Opus 4.5 commited on
Commit
0058591
·
1 Parent(s): bb1f78e

Add classification matrix heatmap visualization

Browse files

New 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>

Files changed (1) hide show
  1. app.py +110 -8
app.py CHANGED
@@ -633,6 +633,91 @@ def sanitize_model_name(model: str) -> str:
633
  return sanitized[:40]
634
 
635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
636
  def create_distribution_chart(result_df, categories, classify_mode="Single Model", models_list=None):
637
  """Create a bar chart showing category distribution.
638
 
@@ -1582,15 +1667,32 @@ with col_output:
1582
  if st.session_state.results:
1583
  results = st.session_state.results
1584
 
1585
- # Distribution chart
1586
- fig = create_distribution_chart(
1587
- results['df'],
1588
- results['categories'],
1589
- classify_mode=results.get('classify_mode', 'Single Model'),
1590
- models_list=results.get('models_list', [])
1591
  )
1592
- st.pyplot(fig)
1593
- st.caption("Note: Categories are not mutually exclusive—each item can belong to multiple categories.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1594
 
1595
  # Results dataframe (hide technical columns from display)
1596
  display_df = results['df'].copy()
 
633
  return sanitized[:40]
634
 
635
 
636
+ def create_classification_heatmap(result_df, categories, classify_mode="Single Model", models_list=None):
637
+ """Create a binary heatmap showing classification for each row.
638
+
639
+ Args:
640
+ result_df: DataFrame with classification results
641
+ categories: List of category names
642
+ classify_mode: "Single Model", "Model Comparison", or "Ensemble"
643
+ models_list: List of model names (for multi-model modes)
644
+ """
645
+ import numpy as np
646
+
647
+ total_rows = len(result_df)
648
+ if total_rows == 0:
649
+ fig, ax = plt.subplots(figsize=(10, 4))
650
+ ax.text(0.5, 0.5, 'No data to display', ha='center', va='center', fontsize=14)
651
+ ax.axis('off')
652
+ return fig
653
+
654
+ # Build the binary matrix based on classify_mode
655
+ if classify_mode == "Ensemble":
656
+ # Use consensus columns
657
+ col_names = [f"category_{i}_consensus" for i in range(1, len(categories) + 1)]
658
+ elif classify_mode == "Model Comparison" and models_list:
659
+ # Use first model's columns for the heatmap
660
+ sanitized = sanitize_model_name(models_list[0])
661
+ col_names = [f"category_{i}_{sanitized}" for i in range(1, len(categories) + 1)]
662
+ else:
663
+ # Single model
664
+ col_names = [f"category_{i}" for i in range(1, len(categories) + 1)]
665
+
666
+ # Extract the binary matrix
667
+ matrix_data = []
668
+ for col in col_names:
669
+ if col in result_df.columns:
670
+ matrix_data.append(result_df[col].astype(int).values)
671
+ else:
672
+ matrix_data.append(np.zeros(total_rows, dtype=int))
673
+
674
+ matrix = np.array(matrix_data).T # Rows = responses, Cols = categories
675
+
676
+ # Create figure with appropriate sizing
677
+ fig_height = max(4, min(20, total_rows * 0.15))
678
+ fig_width = max(8, len(categories) * 0.8)
679
+ fig, ax = plt.subplots(figsize=(fig_width, fig_height))
680
+
681
+ # Create custom colormap: black (0) and green (1)
682
+ from matplotlib.colors import ListedColormap
683
+ cmap = ListedColormap(['#1a1a1a', '#22c55e'])
684
+
685
+ # Plot heatmap
686
+ im = ax.imshow(matrix, aspect='auto', cmap=cmap, vmin=0, vmax=1)
687
+
688
+ # Set labels
689
+ ax.set_xticks(range(len(categories)))
690
+ ax.set_xticklabels(categories, rotation=45, ha='right', fontsize=9)
691
+ ax.set_xlabel('Categories', fontsize=11)
692
+ ax.set_ylabel('Responses', fontsize=11)
693
+
694
+ # Limit y-axis labels for large datasets
695
+ if total_rows > 50:
696
+ # Show fewer tick marks
697
+ tick_step = max(1, total_rows // 20)
698
+ ax.set_yticks(range(0, total_rows, tick_step))
699
+ else:
700
+ ax.set_yticks(range(total_rows))
701
+
702
+ title = 'Classification Matrix'
703
+ if classify_mode == "Ensemble":
704
+ title += ' (Ensemble Consensus)'
705
+ elif classify_mode == "Model Comparison":
706
+ title += f' ({models_list[0].split("/")[-1].split(":")[0][:20]})'
707
+ ax.set_title(title, fontsize=14, fontweight='bold')
708
+
709
+ # Add legend
710
+ from matplotlib.patches import Patch
711
+ legend_elements = [
712
+ Patch(facecolor='#1a1a1a', edgecolor='white', label='Not Present'),
713
+ Patch(facecolor='#22c55e', edgecolor='white', label='Present')
714
+ ]
715
+ ax.legend(handles=legend_elements, loc='upper right', bbox_to_anchor=(1.15, 1))
716
+
717
+ plt.tight_layout()
718
+ return fig
719
+
720
+
721
  def create_distribution_chart(result_df, categories, classify_mode="Single Model", models_list=None):
722
  """Create a bar chart showing category distribution.
723
 
 
1667
  if st.session_state.results:
1668
  results = st.session_state.results
1669
 
1670
+ # Visualization selector
1671
+ viz_type = st.selectbox(
1672
+ "Visualization",
1673
+ options=["Category Distribution", "Classification Matrix"],
1674
+ key="viz_type",
1675
+ help="Distribution shows category percentages. Matrix shows each response's classifications."
1676
  )
1677
+
1678
+ if viz_type == "Category Distribution":
1679
+ fig = create_distribution_chart(
1680
+ results['df'],
1681
+ results['categories'],
1682
+ classify_mode=results.get('classify_mode', 'Single Model'),
1683
+ models_list=results.get('models_list', [])
1684
+ )
1685
+ st.pyplot(fig)
1686
+ st.caption("Note: Categories are not mutually exclusive—each item can belong to multiple categories.")
1687
+ else:
1688
+ fig = create_classification_heatmap(
1689
+ results['df'],
1690
+ results['categories'],
1691
+ classify_mode=results.get('classify_mode', 'Single Model'),
1692
+ models_list=results.get('models_list', [])
1693
+ )
1694
+ st.pyplot(fig)
1695
+ st.caption("Green = category present, Black = not present. Each row is one response.")
1696
 
1697
  # Results dataframe (hide technical columns from display)
1698
  display_df = results['df'].copy()