Here is my code. In the last plot I need help nameing the titles: """ def…
- User
Here is my code. In the last plot I need help nameing the titles:
""" def review_topics(topics, segments, num_to_review, plot_topics_dist): """ - For each topic: - print its representation. - print the top 2 segments for M and F. - plot the distribution of the segments on the narrative timeline - sort the topics by their average placement on the narrative timeline
:param plot_topics_dist: :param num_to_review: :param topics: :param segments: :return: """ # the size of the noise cluster is the value of Counts in the first row of the topics dataframe print("Size of noise cluster: ", topics.iloc[0]['Count']) print("Percentage of noise cluster: ", topics.iloc[0]['Count'] / len(segments) * 100) # remove -1 from the topics topics = topics[topics['Topic'] != -1] # sort the topics by their average placement on the narrative timeline topic_per_time = {} for topic_id in topics['Topic']: # calculate the average placement of each topic on the narrative timeline topic_data = segments[segments['top_topic_id'] == topic_id] avg_times = topic_data.segment_timeline.apply(lambda x: np.mean(x)).mean() topic_per_time[topic_id] = avg_times # print(f"Topic {topic_id} average placement on the narrative timeline: {avg_times:.2f}") # sort the topics by their position on the narrative timeline with warnings.catch_warnings(): warnings.simplefilter("ignore") topics['avg_time'] = topics['Topic'].map(topic_per_time) topics.sort_values(by='avg_time', ascending=True, inplace=True) print("\n ~ Topic Representations ~\n") print("Base Representation - C-TF-IDF") for i, row in topics.iterrows(): topic_data = segments[(segments['top_topic_id'] == row['Topic'])] print(f"Topic {row['Topic']}, size: {len(topic_data)} segments, position: {row['avg_time']:.2f}") # print("diversity: 0.1") # print(row['maximal_marginal_01']) # print("diversity: 0.3") # print(row['maximal_marginal_03']) # print("diversity: 0.8") # print(row['maximal_marginal_08']) # print("diversity: 1.") # print(row['maximal_marginal_1']) # print("keybert") # print(row['keybert']) print(row["Representation"]) # Compute overall average weighted top-3 topic probabilities (not by gender) segments['top_3_topics'] = segments['top_3_topics'].apply(ast.literal_eval) # topic_avg_weight = ( # segments.explode('top_3_topics') # .assign( # top_3_tuple=lambda df: df['top_3_topics'].apply(lambda x: tuple(x) if isinstance(x, list) else x), # topic_id=lambda df: df['top_3_tuple'].apply(lambda t: t[0] if isinstance(t, tuple) else None), # weight=lambda df: df['top_3_tuple'].apply(lambda t: t[1] if isinstance(t, tuple) else None) # ) # .groupby('topic_id')['weight'] # .mean() # .reset_index() # .rename(columns={'topic_id': 'top_topic_id', 'weight': 'avg_weight'}) # ) # now print topic representation by the weighted avg of the top three topics # TODO # for each topic, get the top 2 segments for M and F for topic_id in topics['Topic']: m_df = segments[(segments['top_topic_id'] == topic_id) & (segments['gender'] == 'M')].nlargest(num_to_review, 'top_topic_weight') f_df = segments[(segments['top_topic_id'] == topic_id) & (segments['gender'] == 'F')].nlargest(num_to_review, 'top_topic_weight') if num_to_review > 0: for gender, selected_df in {"M": m_df, "F": f_df}.items(): print(f"~\n Top segments for topic {topic_id} and gender {gender}: \n~") for i, row in selected_df.iterrows(): # print(f"Topic {row['top_topic_id']}:") print("\nSegment id: ", row.name) print(row['text']) # plot these average values # Create x-tick labels with period names x_values = [val for _, val in topic_per_time.items()] x_labels = [f"{avg:.2f}, topic: {topic_id}" for topic_id, avg in topic_per_time.items()] # Period with average value # Use dummy y-values y_values = [1] * len(x_values) # Plot plt.figure(figsize=(18, 3)) plt.scatter(x_values, y_values, s=50) # Customize x-axis plt.xticks(x_values, x_labels, rotation=90, ha="right", fontsize=14) # Label each point with period and value plt.xlabel("Narrative timeline") plt.yticks([]) # Remove y-axis labels plt.ylim(0.9, 1.1) # Keep y-range minimal to emphasize x-axis # tighten the layout plt.tight_layout() # save the figure plt.savefig(f"topics_per_time.png", dpi=1200, bbox_inches='tight') plt.show() # in addition, for each topic plot the distribution of the segments on the narrative timeline if plot_topics_dist: for topic_id in topics['Topic']: topic_data = segments[segments['top_topic_id'] == topic_id] # plot the distribution of the segments on the narrative timeline plt.figure(figsize=(10, 3)) sns.histplot(data=topic_data.segment_timeline.apply(lambda x: np.mean(x)), bins=50, alpha=0.7) plt.title(f"Distribution of segments for topic {topic_id} on the narrative timeline") plt.xlabel("Narrative timeline") plt.ylabel("Number of segments") # save the figure plt.savefig(f"topic_{topic_id}_distribution.png", dpi=1200, bbox_inches='tight') plt.show() # Count the number of segments per topic and gender topic_gender_counts = segments.groupby(['top_topic_id', 'gender']).size().reset_index(name='count') bar_plot_topic_per_gender(topic_gender_counts, list(topics['Topic']), x_col='top_topic_id', col='count') weight_df = compute_weighted_avg_topic_prob(segments) bar_plot_topic_per_gender(weight_df, list(topics['Topic']), x_col='topic_id', col='total_weight', title='Weighted Sum per Topic', y_title='Sum of top-3-topic id weights') # Sum of Topic Weights bar_plot_topic_per_gender(weight_df, list(topics['Topic']), x_col='topic_id', col='normalized_weight', title='Normalized Weighted Sum per Topic') # in addition, we need to plot the bar plot of the topics in their natural order (1-18) # and convert the number of segments to percentages # so instead of 78 segments for some topic, we will have 78/total_segments * 100 total_segments = len(segments) topic_gender_counts['percentage_segs'] = topic_gender_counts['count'] / total_segments * 100 bar_plot_topic_per_gender(topic_gender_counts, [i for i in range(19)], x_col='top_topic_id', col='percentage_segs', title='Percentage of Segments per Topic', y_title='Percentage of Segments in Topic', ) return topics - Assistant
It looks like you're asking about naming the titles for the last plot in your review_topics function. The last plot is created with this call: pythonCopyEditbar_plot_topic_per_gender(topic_gender_counts, [i for i in range(19)], x_col='top_topic_id', col='percentage_segs', title='Percentage of Segments per Topic', y_title='Percentage of Segments in Topic', )
Currently, you already pass a title argument: title='Percentage of Segments per Topic' and a y_title argument: y_title='Percentage of Segments in Topic'. How to Improve or Modify the Titles If you want dynamic titles (e.g., based on data or the number of topics), you can do something like: pythonCopyEdittitle = f'Percentage of Segments per Topic (Total Segments = {total_segments})' y_title = 'Percentage of Segments (%)'
- User
No. Can you add the values above each bar?
- Assistant
To add values above each bar in your bar plot, you'll need to modify the bar_plot_topic_per_gender function (which you’re calling multiple times) to annotate the bars with their respective values. Here’s how you can do it:
Modify bar_plot_topic_per_gender If you’re using matplotlib or seaborn, after plotting, you can add this snippet: pythonCopyEditfor p in ax.patches: ax.annotate(f'{p.get_height():.1f}', (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='bottom', fontsize=10, color='black', xytext=(0, 5), textcoords='offset points')
Example Integration Assume your bar_plot_topic_per_gender function looks something like this: pythonCopyEditdef bar_plot_topic_per_gender(df, topic_list, x_col, col, title=None, y_title=None): plt.figure(figsize=(12, 6)) ax = sns.barplot(data=df[df[x_col].isin(topic_list)], x=x_col, y=col, hue='gender') ax.set_title(title if title else '') ax.set_ylabel(y_title if y_title else '') ax.set_xlabel('Topics')
# Add values above bars for p in ax.patches: ax.annotate(f'{p.get_height():.1f}', (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='bottom', fontsize=10, color='black', xytext=(0, 5), textcoords='offset points') plt.tight_layout() plt.show()