使用ggplot2绘制双连续变量条形图:按区间求和展示
Got it, you want a chart that looks like a histogram, but instead of counting observations per ratio bin, you're summing the amount values in each bin. Here are two straightforward ways to do this with ggplot2:
Option 1: Use stat_summary_bin (No Pre-Processing Needed)
This method lets ggplot handle the binning and summing directly, so you don't have to modify your original data frame first.
First, let's create some sample data to work with (replace this with your actual data):
set.seed(123) # For reproducible results your_data <- data.frame( ratio = runif(1000, 0, 1), # Random values between 0 and 1 amount = rnorm(1000, 50, 10) # Random amounts centered at 50 )
Now the plotting code:
library(ggplot2) ggplot(your_data, aes(x = ratio, y = amount)) + # Sum amount in each bin, use column geom (matches histogram style) stat_summary_bin( fun = sum, geom = "col", bins = 10, # Adjust to change number of equal-width bins fill = "#3498db", color = "white", na.rm = TRUE # Handle any missing values ) + # Add clear labels and title labs( x = "Ratio Intervals", y = "Total Amount per Interval", title = "Total Amount Grouped by Ratio Bins" ) + # Clean, modern theme theme_minimal()
Key Customizations:
- Replace
bins = 10withbreaks = c(0, 0.2, 0.5, 1)if you want custom interval breaks (e.g., 0-0.2, 0.2-0.5, 0.5-1) instead of equal-width bins. - Tweak
fillandcolorvalues to match your preferred color scheme.
Option 2: Pre-Process Data with dplyr (More Control)
If you want to explicitly inspect the binned data and sums before plotting, use this method to pre-process your data first.
library(dplyr) library(ggplot2) # Step 1: Bin the ratio variable and calculate total amount per bin binned_data <- your_data %>% # Create discrete bins (adjust breaks to your needs) mutate(ratio_bin = cut(ratio, breaks = seq(0, 1, by = 0.1))) %>% # Group by each bin and sum the amount group_by(ratio_bin) %>% summarize(total_amount = sum(amount, na.rm = TRUE)) %>% ungroup() # Step 2: Plot the pre-processed data ggplot(binned_data, aes(x = ratio_bin, y = total_amount)) + geom_col(fill = "#e74c3c", color = "white") + labs( x = "Ratio Intervals", y = "Total Amount per Interval", title = "Total Amount Grouped by Ratio Bins" ) + theme_minimal() + # Rotate x-axis labels to prevent overlap theme(axis.text.x = element_text(angle = 45, hjust = 1))
Why This Works:
cut()converts your continuousratiovariable into discrete interval categories, making it easy to group by.summarize(sum(amount))calculates the exact total amount for each bin.geom_col()plots these sums as solid bars, mirroring the look of a traditional histogram.
Both methods will give you the chart you're looking for—pick whichever fits your workflow better!
内容的提问来源于stack exchange,提问作者Cesar Hernandez

