Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

r - 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))

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...