Fake data:
df = data.frame(year = as.factor(1800:2000),
variable = rnorm(length(1800:2000)))
Your plot with fake data:
ggplot(df, aes(x = year, y = variable, group = 1)) +
geom_line()
The problem is that your year variable is a factor
(or maybe a string?), so it's interpreted as categorical. You can work within this framework:
ggplot(df, aes(x = year, y = variable, group = 1)) +
geom_line() +
scale_x_discrete(breaks = levels(df$year)[c(T, rep(F, 9))])
Or, even better, you can convert it to numeric and things work automatically:
df$real_year = as.numeric(as.character(df$year))
ggplot(df, aes(x = real_year, y = variable)) +
geom_line()
Notice that this, doing it "the right way", you don't have to bother with group = 1
or mess with the scale. ggplot rewards you having your data in a proper format: fix your data and you won't have to fix your plot. If you want to make sure the labels are exactly every 10 years, you can use scale_x_continuous
as suggested by user2034412, but by default it will make a good guess at "pretty" breaks in the axis.
If your x-axis is an actual date or datetime, something like 1984-10-31
then you should convert it to a Date
object (or maybe a POSIX
object if it has time as well), and again ggplot
will then know how to handle it appropriately. See ?strftime
(base function) or the lubridate
package for conversions to appropriate date classes.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…