Help def topicpositionheatmap(): segmentsdf, topicsdf = loadsegmentstopics() 1. Bin…
- User
Help
def topic_position_heatmap(): segments_df, topics_df = load_segments_topics() # 1. Bin positions into discrete segments num_bins = 20 segments_df["pos_bin"] = pd.cut(segments_df["position"], bins=num_bins, labels=False)
# 2. Compute average topic presence per bin # TODO - consider taking the top 3 topics per segment and their weights heatmap_data = ( segments_df.groupby(["en_name", "pos_bin"]) .agg(weight=("position", "size")) .reset_index() .pivot(index="en_name", columns="pos_bin", values="weight") .fillna(0) ) # 3. Normalize per-topic (optional, for visual contrast) heatmap_data = heatmap_data.div(heatmap_data.max(axis=1), axis=0) # heatmap_data = heatmap_data / heatmap_data.values.max() topic_order = heatmap_data.apply(lambda x: np.argmax(x.values), axis=1).sort_values().index # 4. Plot heatmap plt.figure(figsize=(14, len(heatmap_data) * 0.4)) ax = sns.heatmap( heatmap_data.loc[topic_order], cmap="YlGnBu", # "rocket_r", cbar_kws={'label': 'Topic Intensity'}, # linewidths=0.05 ) # Enlarge colorbar label and tick labels cbar = ax.collections[0].colorbar cbar.ax.yaxis.label.set_size(14) plt.xlabel("Narrative Timeline", fontsize=16) plt.ylabel("", fontsize=16) plt.title("Distribution of Topics Along the Narrative Timeline") bin_edges = pd.cut(segments_df["position"], bins=num_bins, retbins=True)[1] plt.xticks( ticks=np.arange(num_bins)[e6b5:539c:44ae:3b60:f781:91db:614d:f7dd]+[1.0], labels=[f"{b:.1f}" for b in bin_edges[:-1][e6b5:539c:44ae:3b60:f781:91db:614d:f7dd]]+[1.0], fontsize=12, # rotation=45 ) # y-ticks fontsize plt.yticks(fontsize=14) plt.tight_layout() plt.show() - Assistant
- User
I want to show 1.0 aswell
- Assistant
Ah, got it! You want the x-axis to go from 0.0 → 1.0 and include 1.0 as the last tick, while still showing every other bin along the way. Here's a clean way to do it: pythonCopy code# Get bin edges bin_edges = pd.cut(segments_df["position"], bins=num_bins, retbins=True)[1]
Take every other bin for labels
tick_indices = np.arange(0, num_bins, 2) tick_labels = [f"{bin_edges[i]:.2f}" for i in tick_indices]
Add 1.0 as the last tick
tick_indices = np.append(tick_indices, num_bins - 1) tick_labels.append("1.0")
Set xticks (centered over bins)
plt.xticks(ticks=tick_indices + 0.5, labels=tick_labels, fontsize=12)
✅ Notes:
tick_indices + 0.5 centers the tick over each bin in sns.heatmap.
The last tick is exactly 1.0.
Every other bin is still labeled along the axis.
This will give you: Copy code0.00 0.10 0.20 ... 1.0
If you want, I can rewrite your full plotting function with this incorporated so it works cleanly end-to-end. Do you want me to do that?