# merge the topic mapping with the predictions
df = pd.merge(df, topic_df, how='left', on=['tid', 'text'])
# load the metadata
meta_data = pd.read_csv(METADATA_PATH, index_col=0)
# rename the columns to match the expected format
meta_data.rename(columns=META_COLS, inplace=True)
meta_data['tid'] = meta_data['Identifier'].apply(lambda x: x.split(".")[-1])
# merge the metadata with the predictions
df = pd.merge(df, meta_data, how='left', on=['tid'])
gender_age_df = pd.read_csv(GENDER_AGE_PATH, index_col=0)
gender_age_df.rename(columns={"מגדר": "gender",
"שנת לידה": "year_of_birth"}, inplace=True)
gender_age_df['tid'] = gender_age_df['Testimony Identifier'].apply(lambda x: x.split(".")[-1])
df = pd.merge(df, gender_age_df, how='left', on=['tid'])
# save
df = df[['tid', 'tid_order', 'name', 'text', 'topic_id', 'gender', 'year_of_birth', 'location', ]]
# drop any duplicate rows - according to tid and text
df.drop_duplicates(subset=['tid', 'text'], inplace=True)
df.to_csv(f"domestic_resilience_predictions_{seg_method}_with_metadata_{DATE}.csv")
return df
Assistant
To complete the missing implementation, we need to define the visualizations(data) function that creates:
A heatmap showing the distribution of topic_id by year_of_birth.
With the shading implying age (younger = darker).
We assume year_of_birth is numeric and topic_id is categorical.
Here’s the completed implementation with seaborn for the heatmap:
pythonCopyEditimport matplotlib.pyplot as plt
import seaborn as sns
def visualizations(data):
"""
- create visualizations for the domestic resilience data
- plot a heatmap for each topic id as a function of the year_of_birth (darker means younger)
:param data:
:return:
"""
# Drop missing or invalid data
plot_data = data[['topic_id', 'year_of_birth']].dropna()
plot_data = plot_data[plot_data['year_of_birth'].apply(lambda x: str(x).isdigit())]
plot_data['year_of_birth'] = plot_data['year_of_birth'].astype(int)
User
I had something else in mind. For each topic, I want to visualize its distribution along the year of birth
Assistant
Got it! You want a separate plot for each topic, showing the distribution of year of birth (i.e., how age varies within each topic). This is more like a set of histograms or KDE plots, one per topic, where x = year_of_birth, y = count/density.
Here’s how you can implement that:
✅ Updated visualizations(data) function:
pythonCopyEditimport matplotlib.pyplot as plt
import seaborn as sns
import os
def visualizations(data):
"""
For each topic, plot the distribution of year of birth of testimonies.
This helps understand the age composition of each topic.
"""
# Ensure output directory exists
os.makedirs("topic_birth_year_distributions", exist_ok=True)
User
What other analysis can be done?
Assistant
Great question. Once your data includes topic ID, year of birth, gender, location, and labels for "domestic resilience" (DR), you can run a variety of insightful analyses to explore themes, demographic patterns, and behavioral signals in the testimonies.
🧠 1. Age and Topic Correlation
Goal: See which topics are more common among younger vs. older individuals.
User
Yes.
Implement Geographic Distribution
Assistant
Great! Here's how to implement Geographic Distribution by Topic:
✅ Goal:
Create a heatmap showing how different topics are distributed across locations.
📦 Code to Add to visualizations(data):
pythonCopyEditdef visualize_geographic_distribution(data):
"""
Creates a heatmap of topic occurrence by location.
Helps reveal geographic trends in topic relevance.
"""
code
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
def load_predictions(path2preds):
"""
Load the predictions from a CSV file.
:param path2preds:
:return:
"""
df = pd.read_csv(path2preds)
# filter positive predictions only
df = df[df['gpt4.1_out']]
# rename columns to match the expected format
df.rename(columns={'gpt4.1_out': 'label'}, inplace=True)
df["tid"] = df.tid_order.apply(lambda x: x.split("_")[0].split("#")[0])
code
# in the eq_len segmentation method, the tid_order got messed up, but the tid is still correct
# so we need to fix the tid_order
order_series = df.groupby('tid').cumcount() + 1
df['tid_order'] = df.tid + "_" + order_series.astype(str)
# ensure the columns are in the right order
return df[['tid', 'tid_order', 'text', 'label']]
def organize_data():
parser = ArgumentParser(description="Analyze domestic resilience data")
parser.add_argument('--predictions', type=str, required=True,
help="Path to the predictions file with DR classifications")
parser.add_argument('--seg_method', type=str, required=True,
choices=['eq_len', 'unsupervised'],
help="Segmentation method used for the data")
parser.add_argument('--topic_map', type=str, required=True,
help="Path to the topic mapping file")
args = parser.parse_args()
data = load_predictions(args.predictions)
return incorporate_metadata(data, args.topic_map, args.seg_method)
def visualizations(data):
"""
- create visualizations for the domestic resilience data
- plot a heatmap for each topic id as a function of the year_of_birth (darker means younger)
:param data:
:return:
"""
pass
if name == 'main':
"""
- load the data segments and their classifications based on DR prompt
- load the list segments mapped to topics
- load the metadata of the testimonies
- load the gender and age of the testimonies
# Create a pivot table of counts: rows = topic_id, columns = year_of_birth
heatmap_data = plot_data.pivot_table(index='topic_id',
columns='year_of_birth',
aggfunc='size',
fill_value=0)
# Reverse the columns so that younger years (larger numbers) are on the right
heatmap_data = heatmap_data[sorted(heatmap_data.columns, reverse=True)]
plt.figure(figsize=(14, 8))
sns.heatmap(heatmap_data, cmap="Blues", cbar_kws={'label': 'Number of Testimonies'})
plt.title('Distribution of Year of Birth per Topic')
plt.xlabel('Year of Birth (younger →)')
plt.ylabel('Topic ID')
plt.tight_layout()
plt.savefig(f"topic_year_of_birth_heatmap_{DATE}.png")
plt.show()
Optional: Add to main
If you want to call this directly in your main block after organize_data():
pythonCopyEditif name == 'main':
df = organize_data()
visualizations(df)
Let me know if you'd like additional plots or demographic breakdowns (e.g., gender-based distributions).
code
# Filter out rows with missing or non-numeric year_of_birth
plot_data = data[['topic_id', 'year_of_birth']].dropna()
plot_data = plot_data[plot_data['year_of_birth'].apply(lambda x: str(x).isdigit())]
plot_data['year_of_birth'] = plot_data['year_of_birth'].astype(int)
# Sort topic ids for consistent output
topic_ids = sorted(plot_data['topic_id'].unique())
for topic in topic_ids:
topic_df = plot_data[plot_data['topic_id'] == topic]
plt.figure(figsize=(8, 4))
sns.histplot(topic_df['year_of_birth'], bins=20, kde=True, color='skyblue')
plt.title(f"Year of Birth Distribution for Topic {topic}")
plt.xlabel("Year of Birth")
plt.ylabel("Count")
plt.grid(True)
plt.tight_layout()
# Save individual plots
plt.savefig(f"topic_birth_year_distributions/topic_{topic}_birth_year_distribution_{DATE}.png")
plt.close()
🔎 What this does:
Saves one PNG per topic under topic_birth_year_distributions/
Uses both histogram and KDE for better visual clarity
Automatically filters out bad year values
📦 Optional addition to main:
If you want to auto-generate plots after running:
pythonCopyEditif name == 'main':
df = organize_data()
visualizations(df)
Would you like all the plots also compiled into a single PDF, or displayed in a grid layout (like a facet plot)?
How:
Compute mean/median year_of_birth per topic_id
Plot bar chart: topic vs. average year_of_birth (or age)
🚻 2. Gender vs. Topic Distribution
Goal: Identify gendered experiences or expression of topics
How:
Count of topic_id per gender
Stacked bar chart or heatmap
Optionally normalized (e.g. percentage)
🗺️ 3. Geographic Distribution
Goal: Which topics are associated with different locations (e.g., towns, kibbutzim)
How:
Cross-tabulation: topic_id vs location
Heatmap of frequencies or normalized proportions
📊 4. DR Label by Demographics
Goal: Analyze who exhibits more "domestic resilience" (based on the label)
How:
Proportion of positive labels by:
Gender
Age groups (e.g., <40, 40–60, >60)
Location
Topic
Bar plots or violin plots of age distribution by label
🔍 5. Topic Co-occurrence or Sequencing
Goal: Are certain topics often sequential or clustered per testimony?
How:
Group by tid and look at ordered topic_ids (using tid_order)
Create co-occurrence matrices or Sankey diagrams
🧩 6. Topic Embedding Clusters
Goal: Use dimensionality reduction to cluster similar topics
How:
Use embeddings (from BERTopic or similar) and apply UMAP + clustering
Visualize in 2D space colored by average age/gender
💬 7. Textual Differences by Age/Gender
Goal: Do word choices vary across demographic lines?
How:
Word clouds or TF-IDF analysis split by:
Younger vs. older groups
Male vs. female
Compare linguistic patterns
📅 8. Testimony Temporal Segments
If your data includes when the segments occur in the testimony:
Plot how topic coverage evolves over time in testimonies.
See if younger people follow different "narrative arcs".
Would you like help implementing one of these? I can generate code for the most relevant one based on your goals.
import matplotlib.pyplot as plt
import seaborn as sns
import os
os.makedirs("geo_distributions", exist_ok=True)
# Clean data
geo_data = data[['topic_id', 'location']].dropna()
geo_data = geo_data[geo_data['location'].str.strip() != ""]
# Count occurrences
location_topic_matrix = geo_data.pivot_table(index='location',
columns='topic_id',
aggfunc='size',
fill_value=0)
# Filter to show most frequent locations if too many
top_locations = location_topic_matrix.sum(axis=1).sort_values(ascending=False).head(20).index
filtered_matrix = location_topic_matrix.loc[top_locations]
plt.figure(figsize=(12, 8))
sns.heatmap(filtered_matrix, cmap="Purples", annot=True, fmt="d",
cbar_kws={'label': 'Number of Testimonies'})
plt.title("Topic Distribution by Location (Top 20 Locations)")
plt.xlabel("Topic ID")
plt.ylabel("Location")
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig(f"geo_distributions/topic_by_location_heatmap_{DATE}.png")
plt.show()
🔁 Update your main:
To generate this along with other visualizations:
pythonCopyEditif name == 'main':
df = organize_data()
visualizations(df)
visualize_geographic_distribution(df)
📝 Notes:
You can tweak head(20) to show more/less locations.
annot=True shows exact numbers in cells.
Consider normalizing rows if you want percentages per location rather than absolute counts.