I'm trying to reproduce a base plot using ggplot2, and I'm struggling with the tick labels. In the base plot, tick labels are automatically dropped to prevent label collisions, or overlap. In ggplot2, I can't find any way to achieve the same results. I feel as though I must be missing something.
Unfortunately, while I can ask the user for tick labels, I can't ask the user for breaks because I'm plugging my code into an existing app. If I have to manually set breaks and labels, it looks like I'll have to come up with a custom version of pretty() (or pretty_breaks()) that handles non-numeric labels.
Below is a minimum reproducible example, and attached are example plots. With a plot window narrow enough, you'll see that the base plot automatically drops labels, but the ggplot2 version keeps all labels and overlaps the text.
my_vec <- c(5045,4350,4350,3975,4290,4430,4485,4285,3980,3925,3645,3760,3300,3685,3463,5200)
my_labels <- c("alpha","beta","gamma","delta","epsilon","zeta","eta","theta","iota","kappa","lambda","mu","nu","xi","omicron","pi")
index_v <- 1:(length(my_vec))
names(my_vec) <- my_labels
# Convert to data frame for ggplot2
my_df <- data.frame(indices = index_v, values = my_vec, data_labels = my_labels)
# Plot using base; the x-axis labels work the way we want
plot(index_v, my_vec, type="n",
axes = FALSE, main = "Title")
lines(index_v, my_vec, type = "b", pch=20)
# Plot using ggplot2: labels either overlap or throw an error
ggplot(my_df, aes(x = indices, y = values)) +
geom_line(stat = "identity") +
scale_x_continuous(breaks = my_df$indices, labels = my_df$data_labels)
# Depending on plot width, this results in overlapping labels
# We want to reduce the number of breaks (and matching labels) so that labels
# don't overlap, as happens automatically in the base plot.
# \code{breaks =} is not supplied, then we get an error:
# Error in f(..., self = self) : Breaks and labels are different lengths