You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python绘制词/短语频率及占比的气泡图?

How to Create a Bubble Chart for Word Frequencies & Percentages in Python

Hey there! Let's build that bubble chart you need. We'll use pandas for smooth data handling and matplotlib for plotting (super common, flexible tools). Here's a step-by-step breakdown to get you what you want:

Step 1: Prep Data & Calculate Percentages

First, we'll turn your raw tuple list into a pandas DataFrame—it makes calculating percentages and organizing data way simpler.

import pandas as pd
import matplotlib.pyplot as plt

# Your raw phrase-frequency data
data = [('thank_you', 13443), ('best_regards', 9833), ('cloud_product', 9658), 
        ('support_eng', 8147), ('your_x', 8106), ('expert_fx', 8103), 
        ('accreditation_program', 8066), ('http_communitys', 7940)]

# Convert to a structured DataFrame
df = pd.DataFrame(data, columns=['phrase', 'count'])

# Calculate total count and percentage share for each phrase
total_count = df['count'].sum()
df['percentage'] = round((df['count'] / total_count) * 100, 2)

Step 2: Plot the Bubble Chart

We'll use plt.scatter() to create bubbles, where:

  • X-axis: Sequential positions for each phrase (since we're dealing with categorical data)
  • Y-axis: Frequency count (easy to swap to percentage if you prefer)
  • Bubble size: Tied to frequency count (scaled to fit the plot nicely—tweak the multiplier as needed)
  • Text labels: Show each phrase, its count, and percentage directly on/near the bubble
# Set up plot dimensions
plt.figure(figsize=(12, 7))

# Define plot positions and bubble size
x = range(len(df))
y = df['count']
bubble_sizes = df['count'] * 0.8  # Adjust this multiplier to resize bubbles

# Draw the bubbles
scatter = plt.scatter(x, y, s=bubble_sizes, alpha=0.6, color='#2c3e50')

# Add text labels for every bubble
for i, row in df.iterrows():
    plt.text(x[i], y[i], 
             f"{row['phrase']}\nCount: {row['count']}\n%: {row['percentage']}%",
             ha='center', va='center', fontsize=10)

# Customize plot styling
plt.title('Phrase Frequency Bubble Chart', fontsize=14, pad=20)
plt.xticks(x, df['phrase'], rotation=45, ha='right')
plt.ylabel('Frequency Count', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)

# Adjust layout to prevent label cutoff
plt.tight_layout()

# Show the final plot
plt.show()

Quick Customization Tips

  • Swap bubble size metric: To tie bubble size to percentage instead of count, change bubble_sizes = df['percentage'] * 50 (adjust the multiplier to get the right bubble scale)
  • Switch Y-axis to percentages: Replace y = df['count'] with y = df['percentage'] and update the Y-axis label to "Percentage Share"
  • Interactive plot option: For hover tooltips and zoom/pan functionality, use plotly.express instead. Here's a quick snippet:
import plotly.express as px

fig = px.scatter(df, x='phrase', y='count', size='count', 
                 text=['<b>{}</b><br>Count: {}<br>%: {}%'.format(p, c, perc) for p, c, perc in zip(df['phrase'], df['count'], df['percentage'])],
                 size_max=60)
fig.update_layout(title='Phrase Frequency Bubble Chart', xaxis_tickangle=-45)
fig.show()

内容的提问来源于stack exchange,提问作者Baktaawar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:37:40