import numpy as np import matplotlib.pyplot as plt Define your custom bins bins = [0,…
- User
import numpy as np import matplotlib.pyplot as plt
Define your custom bins
bins = [0, 1.5, 2.5, 3.5, 4.5, 5.5, 10.5, 20.5, 50.5, 100.5, 500.5, 1000.5, 5000.5, 1000000]
Compute the histogram counts using NumPy
counts, bin_edges = np.histogram(df_blocks.Size, bins=bins)
Create custom bin labels
bin_labels = [ "1", # 0-1 "2", # 1-2 "3", # 2-3 "4", # 3-4 "5", # 4-5 "6-10", # 5-10 "11-20", # 10-20 "21-50", # 20-50 "51-100", # 50-100 "101-500",# 100-500 "501-1k", # 500-1000 "1k-5k", # 1000-5000 "5k+" # 5000-100000 ]
Plot using plt.bar with equal bar widths
plt.figure(figsize=(12, 8)) x_positions = np.arange(len(counts)) bars = plt.bar(x_positions, counts, color='skyblue', edgecolor='black', linewidth=1.2)
Add annotations on top of bars
for bar, count in zip(bars, counts): plt.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 1, str(count), ha='center', va='bottom', fontsize=10, color='black')
Customize the plot
plt.xticks(x_positions, bin_labels, rotation=45, fontsize=12) plt.yticks(fontsize=12) plt.title('Distribution of Block Sizes', fontsize=16, fontweight='bold') plt.xlabel('Block Size', fontsize=14) plt.ylabel('Count', fontsize=14) plt.grid(axis='y', linestyle='--', alpha=0.7) plt.tight_layout()
Show the plot
plt.show()
stack bar based on Supercategory (LM, PS, N) showing counts on bar
- Assistant
Below is an example of how you can compute counts for each bin broken down by supercategory (here assumed to be
"LM","PS", and"N") and then plot a stacked bar chart with the counts annotated on each segment of the bars.This example assumes you have a DataFrame called
df_blockswith at least two columns:Sizecontaining the numerical block size, andSupercategorycontaining the category labels (e.g."LM","PS","N").
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Example DataFrame setup (remove or replace with your actual data) # Uncomment the following if you need to simulate some data: # np.random.seed(0) # df_blocks = pd.DataFrame({ # 'Size': np.random.choice(np.concatenate([np.random.randint(1,6,100), # np.random.randint(6,11,100), # np.random.randint(11,21,100), # np.random.randint(21,51,100), # np.random.randint(51,101,100), # np.random.randint(101,501,100), # np.random.randint(501,1001,100), # np.random.randint(1001,5001,100), # np.random.randint(5001,100001,100)]), 900), # 'Supercategory': np.random.choice(['LM', 'PS', 'N'], 900) # }) # Define your custom bins bins = [0, 1.5, 2.5, 3.5, 4.5, 5.5, 10.5, 20.5, 50.5, 100.5, 500.5, 1000.5, 5000.5, 1000000] # Define custom bin labels (corresponding to the bins above) bin_labels = [ "1", # corresponds roughly to Size in (0, 1.5) "2", # 1.5-2.5 "3", # 2.5-3.5 "4", # 3.5-4.5 "5", # 4.5-5.5 "6-10", # 5.5-10.5 "11-20", # 10.5-20.5 "21-50", # 20.5-50.5 "51-100", # 50.5-100.5 "101-500",# 100.5-500.5 "501-1k", # 500.5-1000.5 "1k-5k", # 1000.5-5000.5 "5k+" # 5000.5-1000000 ] # Define the supercategories and (optionally) a color for each categories = ['LM', 'PS', 'N'] colors = ['skyblue', 'salmon', 'lightgreen'] # Compute counts per bin for each supercategory # We'll store the counts for each category into a dictionary. stack_counts = {} for cat in categories: # Filter the DataFrame by the current supercategory cat_data = df_blocks[df_blocks['Supercategory'] == cat]['Size'] counts_cat, _ = np.histogram(cat_data, bins=bins) stack_counts[cat] = counts_cat # Positions for our bars based on the number of bins x_positions = np.arange(len(bin_labels)) # Create the stacked bar chart plt.figure(figsize=(12, 8)) bottom = np.zeros(len(bin_labels)) # to keep track of the lower bound of each stack # Loop through each category and plot its counts on top of what was already plotted. for cat, color in zip(categories, colors): counts = stack_counts[cat] bars = plt.bar(x_positions, counts, bottom=bottom, color=color, edgecolor='black', linewidth=1.2, label=cat) # Annotate each segment in the stacked bar with its count for i, bar in enumerate(bars): count = counts[i] if count > 0: # Place the text at the center of the bar segment plt.text(bar.get_x() + bar.get_width()/2, bottom[i] + count/2, str(count), ha='center', va='center', fontsize=10, color='black') # Update bottom to include the current category counts bottom += counts # Customize the plot appearance plt.xticks(x_positions, bin_labels, rotation=45, fontsize=12) plt.yticks(fontsize=12) plt.title('Distribution of Block Sizes by Supercategory', fontsize=16, fontweight='bold') plt.xlabel('Block Size', fontsize=14) plt.ylabel('Count', fontsize=14) plt.legend(title='Supercategory', fontsize=12) plt.grid(axis='y', linestyle='--', alpha=0.7) plt.tight_layout() plt.show()
Explanation
-
Custom Bins and Labels:
- The
binslist is set so that each bin will capture the desired ranges. - The corresponding
bin_labelsare provided in a simplified form (e.g."1","2", ...,"5","6-10", etc.).
- The
-
Computing Counts by Supercategory:
- For each supercategory (e.g.
"LM","PS","N"), the code filtersdf_blocksand usesnp.histogramto calculate counts per bin. - The counts for each category are stored in the dictionary
stack_counts.
- For each supercategory (e.g.
-
Stacked Bar Plot:
- The stacked bar is built using a loop where each supercategory’s counts are plotted with
plt.barusing thebottomparameter to stack them. - After plotting each segment, we update
bottomto accumulate the counts for the next category.
- The stacked bar is built using a loop where each supercategory’s counts are plotted with
-
Annotations:
- Each segment’s count is annotated inside the bar by computing the vertical center of that segment.
-
Plot Customization:
- The x-ticks are set to the custom bin labels with a 45-degree rotation.
- A legend indicates which color corresponds to which supercategory.
- Grid lines and layout adjustments are added for clarity.
This approach gives you a clear, stacked bar chart where each bin is split by supercategory and every segment shows its count.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.