Reputation: 25
I've got a simple plot with the year on the x axis and population on the y axis. Why does the year have decimal at the end of it? I'm not sure how to format this. It's a numeric in a data frame.
dput(head(that[,c("year","pop")]))
structure(list(year = c(2010, 2011, 2012, 2013, 2014, 2015),
pop = c(9574323, 9657592, 9749476, 9843336, 9932887, 10031646
)), row.names = c("1", "2", "3", "4", "5", "6"), class = "data.frame")
ggplot(that, aes(year, pop)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE )
Upvotes: 2
Views: 1315
Reputation: 160447
You can control the axis breaks (and labels) with scale_x_continuous
. Try this:
ggplot(that, aes(year, pop)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
scale_x_continuous(breaks = seq(ceiling(min(that$year)), floor(max(that$year)), by = 2))
I use ceiling
and floor
to round the numbers, and to push them "inward" on the plot (if fractional). by=2
is arbitrary, it depends on your data. If you need this to be dynamic (various ranges), then seq(from, to, length.out=)
makes sense, but it can lead to fractional years, so you need to do some "math" and logic to determine a reasonable by=
instead, such as
diff(range(that$year))
# [1] 5
diff(range(that$year)) / 4
# [1] 1.25
yearby <- round(diff(range(that$year)) / 4) # assuming you want "4"-ish ticks, more or less
ggplot(that, aes(year, pop)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
scale_x_continuous(breaks = seq(ceiling(min(that$year)), floor(max(that$year)), by = yearby))
Upvotes: 3