如何基于字符频率绘制固定宽度、高度按比例缩放的文本?
Got it, let's build this character plot exactly as you described! Here's a step-by-step solution that gives each character a fixed width and sets its height to how often it appears in the text:
Step 1: Count Character Frequencies
First, we need to tally up how many times each character appears (we'll exclude spaces like in your "hello world" example). Python's collections.Counter is perfect for this quick frequency counting.
Step 2: Prepare Data for Plotting
Extract the unique characters and their corresponding frequencies into separate lists—this will be our x and y data for the plot.
Step 3: Generate the Fixed-Width Plot
Use matplotlib's bar() function with a fixed width for each bar. We'll adjust the x-axis ticks to display the characters instead of numerical positions, so the plot is easy to read.
Here's the full code:
import matplotlib.pyplot as plt from collections import Counter # Input text (replace this with your own text!) text = "hello world" # Count frequencies of non-space characters char_counts = Counter(c for c in text if c != ' ') # Split into characters and their respective heights (frequencies) chars = list(char_counts.keys()) heights = list(char_counts.values()) # Set fixed width for each character bar bar_width = 1 # Create the plot fig, ax = plt.subplots(figsize=(8, 4)) # Optional: adjust figure size # Draw bars with fixed width ax.bar(range(len(chars)), heights, width=bar_width) # Align character labels with the center of each bar ax.set_xticks([i + bar_width/2 for i in range(len(chars))]) ax.set_xticklabels(chars) # Add labels and title ax.set_title("Character Frequency (Fixed Width Bars)") ax.set_ylabel("Frequency (Bar Height)") ax.set_xlabel("Characters") # Adjust layout to prevent label cutoff plt.tight_layout() # Show the plot plt.show()
What this does:
- For your "hello world" example, this will produce a plot where:
- 'l' has a height of 3 (it appears 3 times)
- 'o' has a height of 2 (it appears 2 times)
- All other characters ('d', 'e', 'h', 'r', 'w') have a height of 1
- Every bar has the exact same width (set to 1 here—you can tweak
bar_widthif you want narrower/wider bars, just keep it a fixed value!)
内容的提问来源于stack exchange,提问作者J.G

