How to not show all labels on ggplot axis?

I'm trying to using ggplot2 to plot this: enter image description hereBut as you can see on the x axis you can't read anything...

So how can I show on the x axis the value every 10 years, for example?

This is my command:

ggplot(prova, aes(x=year, y=mass..g.)) + geom_line(aes(group = 1))


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.


Is your year column numeric? You can add scale_x_continuous with a breaks argument to specify where the x axis ticks should be. I can't tell what the range of years is in the image, but if it's from 1900 to 2000 (e.g.) you can do something like this:

ggplot(prova, aes(x=year, y=mass..g.)) +
    geom_line(aes(group=1)) +
    scale_x_continuous(breaks=seq(1900, 2000, 10))

The other answers have covered the case where your dates are numerical years, but if (as @Gregor notes) your dates are actual Date objects, it's a lot easier:

scale_x_date(name = 'My date axis title', date_breaks = '20 years',
        date_labels = '%Y')

With scale_date, you can control the breaks with intuitive language and the labelling with (hopefully) familiar strptime notation.