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

Python实现堆叠点直方图(以堆叠点列替代柱状条)

Stacked Dot Histogram in Python

Got it! I’ve helped folks build this exact visualization before—it’s a fantastic way to show distribution while keeping visibility on individual data points, instead of just aggregated bars. Let’s walk through a complete implementation using matplotlib and numpy (the go-to tools for custom Python visualizations):

Step 1: Core Concept

Instead of drawing a bar for each histogram bin (where height = count), we’ll:

  • Split our data into bins just like a regular histogram
  • For each bin, plot individual points stacked vertically—each point represents one data point in that bin
  • Align points neatly so they don’t overlap (unless you want intentional jitter for dense bins)

Step 2: Full Code Implementation

import numpy as np
import matplotlib.pyplot as plt

# ----------------------
# 1. Prepare your data (replace this with your own dataset!)
# ----------------------
np.random.seed(42)  # For reproducibility
data = np.concatenate([
    np.random.normal(loc=2, scale=0.8, size=50),
    np.random.normal(loc=5, scale=1.2, size=70),
    np.random.normal(loc=8, scale=0.6, size=40)
])

# ----------------------
# 2. Set up histogram bins
# ----------------------
bin_edges = np.arange(0, 10, 0.5)  # Customize bin width as needed
bin_counts, _ = np.histogram(data, bins=bin_edges)
bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2  # X-position for each bin's points

# ----------------------
# 3. Calculate positions for each stacked point
# ----------------------
x_coords = []
y_coords = []
for bin_idx, count in enumerate(bin_counts):
    if count == 0:
        continue
    # X: repeat the bin center for every point in the bin
    x_coords.extend([bin_centers[bin_idx]] * count)
    # Y: stack points vertically (start at 0, increment by 1 per point)
    y_coords.extend(range(count))

# ----------------------
# 4. Plot the stacked dots
# ----------------------
plt.figure(figsize=(10, 6))
plt.scatter(x_coords, y_coords, s=50, color="#2c3e50", alpha=0.8, edgecolor="white")

# ----------------------
# 5. Customize the plot to match your desired style
# ----------------------
plt.xlabel("Value", fontsize=12)
plt.ylabel("Count (Stacked Points)", fontsize=12)
plt.title("Stacked Dot Histogram", fontsize=14, pad=20)
plt.xlim(bin_edges[0] - 0.2, bin_edges[-1] + 0.2)
plt.ylim(-0.5, max(bin_counts) + 0.5)

# Optional: Add grid lines for readability
plt.grid(axis='y', linestyle='--', alpha=0.7)

# Remove top/right spines for cleaner look
plt.gca().spines[['top', 'right']].set_visible(False)

plt.tight_layout()
plt.show()

Step 3: Key Customizations

  • Bin Width: Adjust bin_edges to make bins wider/narrower (e.g., np.arange(0,10,1) for wider bins)
  • Point Style: Change s (size), color, alpha, or marker (e.g., marker='o' or marker='s')
  • Jitter for Dense Bins: If you have bins with hundreds of points, add small random noise to X positions to avoid overcrowding:
    x_coords = [x + np.random.uniform(-0.1, 0.1) for x in x_coords]
    
  • Color Coding: If you want to group data by category, assign different colors to subsets of points (just split your data into groups and plot each group separately)

Step 4: Matching Your Example Visualization

Since you mentioned having an example image, you can tweak the above code to match:

  • Adjust bin positions to align with your example
  • Change point colors/sizes to match the style
  • Add any annotations or labels present in your example

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:45:30