如何拆分长数字为单个字符并使用matplotlib绘制线性升降矩形直方图?
Got it, let's tackle this problem step by step. The sharp transitions you're seeing are almost certainly from matplotlib's default binning logic grouping multiple digits into the same bin—let's fix that with a straightforward, clean approach.
Step 1: Split Your Number into Individual Digits
First, we need to break that long number into a list of single-digit integers. Converting the number to a string makes this trivial:
number = 93283274658402812765 digits = [int(char) for char in str(number)]
Step 2: Plot the Histogram with Digit-Aligned Bins
The key fix is to force the histogram bins to align exactly with each digit (0-9). This ensures every digit gets its own contiguous bar, no gaps, no overlapping, and smooth linear transitions between bars. Here's the code:
import matplotlib.pyplot as plt import numpy as np # Plot the histogram with precise binning plt.hist( digits, bins=np.arange(0, 11), # Creates bins [0,1), [1,2), ..., [9,10) for each digit rwidth=1, # Makes bars fill the entire bin width (no gaps between rectangles) edgecolor='black' # Adds clear edges to define each rectangle ) # Adjust x-ticks to center labels on each bar plt.xticks(np.arange(0, 10) + 0.5, np.arange(0, 10)) # Add context to the plot plt.xlabel('Digit') plt.ylabel('Frequency') plt.title('Frequency of Each Digit in the Number') plt.show()
Alternative: Explicit Bar Chart for Full Control
If you want direct control over the counts, you can tally frequencies first with collections.Counter, then plot a bar chart—this achieves the same linear rectangular result:
from collections import Counter import matplotlib.pyplot as plt # Count frequencies (ensure all digits 0-9 are included, even if count is 0) digit_counts = [Counter(digits).get(d, 0) for d in range(10)] # Plot the bar chart plt.bar( range(10), digit_counts, width=1, # Eliminates gaps between bars edgecolor='black' ) # Set x-ticks to show each digit clearly plt.xticks(range(10)) # Add labels and title plt.xlabel('Digit') plt.ylabel('Frequency') plt.title('Frequency of Each Digit in the Number') plt.show()
Why This Fixes the Sharp Transitions
Your original histogram used matplotlib's default binning, which picks a small number of bins that group multiple digits together. This creates uneven, sharp peaks. By setting bins to np.arange(0,11), we force each digit to occupy its own dedicated bin, resulting in a clean sequence of rectangles that rise and fall smoothly based on each digit's actual frequency.
内容的提问来源于stack exchange,提问作者y33t

