使用scale_x_discrete时标签消失问题及ggplot代码求助
scale_x_discrete Let’s break down why your x-axis labels are vanishing and fix this step by step! I spot a few key issues in your code that are causing the problem:
1. Mismatched Data Type & Scale Type
If your Times column is numeric (integers 0-23), using scale_x_discrete is incorrect—this scale is designed for categorical variables (like text or factors). Using it on numeric data can cause labels to fail rendering properly.
2. Incomplete Theme Settings
Your axis.text.x call cuts off with angle = 90, ...—you’re missing critical alignment parameters (vjust and hjust) that ensure rotated labels don’t get clipped outside the plot area.
3. Redundant/Conflicting Scale Parameters
You defined times = c(0:23) but used it in limits without ensuring your Times data matches that format (e.g., if Times is a factor, numeric limits won’t line up correctly).
Corrected Code (Two Options)
Pick the one that matches your Times data type:
Option 1: If Times is Numeric (Use Continuous Scale)
This is the better fit for hourly integer values:
times <- 0:23 ggplot(TravelTimes, aes(x = Times)) + labs(y = "# Flights", x = "Hour") + scale_x_continuous( breaks = times, # Explicitly set all hour ticks limits = range(times) # Ensure full 0-23 range is displayed ) + geom_point(aes(y = TravelTimes[[2]], colour = "Arrivals", group = 1)) + geom_point(aes(y = TravelTimes[[3]], colour = "Departures", group = 1)) + geom_line(aes(y = TravelTimes[[2]], colour = "Arrivals", group = 1)) + geom_line(aes(y = TravelTimes[[3]], colour = "Departures", group = 1)) + theme( axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1) # Fix label alignment )
Option 2: If You Want Times as a Discrete Factor
First convert Times to a factor to match scale_x_discrete:
# Convert Times to a factor with all 0-23 levels (even if some are missing in data) TravelTimes$Times <- factor(TravelTimes$Times, levels = 0:23) ggplot(TravelTimes, aes(x = Times)) + labs(y = "# Flights", x = "Hour") + scale_x_discrete( breaks = 0:23, # Show all hour labels limits = 0:23 # Ensure full range is included ) + geom_point(aes(y = TravelTimes[[2]], colour = "Arrivals", group = 1)) + geom_point(aes(y = TravelTimes[[3]], colour = "Departures", group = 1)) + geom_line(aes(y = TravelTimes[[2]], colour = "Arrivals", group = 1)) + geom_line(aes(y = TravelTimes[[3]], colour = "Departures", group = 1)) + theme( axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1) # Fix label clipping )
Key Changes Explained:
- Fixed alignment: Added
vjust = 0.5andhjust = 1toaxis.text.xso rotated labels stay within the plot area. - Matched scale to data: Used
scale_x_continuousfor numeric data (more intuitive for hours) or convertedTimesto a factor for discrete scaling. - Simplified parameters: Removed redundant
nameinscale_xsincelabs(x = "Hour")already sets the axis title.
内容的提问来源于stack exchange,提问作者I.J. Abdul Hakeem

