ggplot技术问询:为已分箱变量设置与未分箱图一致的连续标签
To make your second plot's x-axis match the continuous style of the first plot (without modifying your original cut()/Freq() workflow), we can use a custom axis transformation to map the discrete bin factor levels to their numeric midpoints. This will make the x-axis appear continuous, with the same range and break points as your first plot.
Step-by-Step Implementation
First, let's assume your original second plot is stored as p2:
library(DescTools) library(ggplot2) # Original second plot code p2 <- iris$Petal.Length %>% cut(30) %>% Freq() %>% ggplot(aes(x = level, y = freq, group = 1)) + geom_line()
Now, append the following code to convert the x-axis to a continuous style:
library(scales) # Calculate midpoints of the 30 equal-width bins min_pl <- min(iris$Petal.Length) max_pl <- max(iris$Petal.Length) bin_width <- (max_pl - min_pl) / 30 midpoints <- seq(min_pl + bin_width/2, max_pl - bin_width/2, by = bin_width) # Create a custom transformation to map factor codes to bin midpoints bin_trans <- trans_new( name = "bin_midpoint", transform = function(x) midpoints[x], # Map factor index to midpoint inverse = function(x) findInterval(x, midpoints - bin_width/2) + 1 # Reverse for interaction ) # Apply the transformation to your plot p2 + scale_x_continuous( trans = bin_trans, limits = c(min_pl, max_pl), # Match range to first plot breaks = seq(floor(min_pl), ceiling(max_pl), by = 1) # Match break intervals to first plot ) + labs(x = "Petal.Length") # Ensure x-axis label matches first plot
How This Works
- Calculate Bin Midpoints: We first compute the midpoint of each of the 30 equal-width bins using the min/max of
Petal.Length. - Custom Transformation: The
trans_newfunction creates a mapping between the discrete factor indices (1 to 30) and their corresponding bin midpoints. This tells ggplot to treat the discrete x-values as continuous midpoints. - Align Axis with First Plot: We set the x-axis limits to match the full range of
Petal.Lengthand use regular integer breaks, just like your first plot's continuous axis.
Alternative (No Additional Package)
If you prefer not to use the scales package, you can manually set discrete labels to midpoints and style the axis to look continuous:
# Calculate midpoints from the plot's data p2_data <- p2$data p2_data$midpoint <- sapply(strsplit(gsub("[\\(\\)\\[\\]]", "", as.character(p2_data$level)), ","), function(x) mean(as.numeric(x))) # Update the plot p2 + scale_x_discrete( breaks = p2_data$level, labels = round(p2_data$midpoint, 1) ) + theme(axis.text.x = element_text(angle = 0, hjust = 0.5)) + labs(x = "Petal.Length")
This method makes the axis appear continuous by using numeric labels, but note that it's still a discrete scale under the hood. The first method with the custom transformation creates a true continuous axis, which is a closer match to your first plot.
内容的提问来源于stack exchange,提问作者J. Doe

