'How to set years on X axis as integer in ggplot R

I don't know why but when I run ggplot stacked area chart, years on the x-axis are doubles like 2012.5.... I set them as integer but still have this issue. Any solution?

df$Year <- as.integer(df$Year)

order <- df %>% filter(Year ==max(df$Year) ) %>% arrange(desc(Sales)) %>% select(Category)
df$Category <- factor(df$Category, levels = order$Category)

df %>% 
  ggplot(aes(x = Year, y = Sales, fill = Category)) +
  geom_area()

enter image description here



Solution 1:[1]

You can specify the breaks to use with scale_x_continuous().

df %>% 
  ggplot(aes(x = Year, y = Sales, fill = Category)) +
  geom_area() + scale_x_continuous(breaks=2010:2020)

To make it more dynamic and automatically choose the limits base on your data, use:

df %>% 
  ggplot(aes(x = Year, y = Sales, fill = Category)) +
  geom_area() + scale_x_continuous(breaks=min(df$Year):max(df$Year))

And if you don't want to show every year you can use seq() to just have every Nth year. E.g. for every third year:

df %>% 
  ggplot(aes(x = Year, y = Sales, fill = Category)) +
  geom_area() + scale_x_continuous(breaks=seq(min(df$Year),max(df$Year),3))

Solution 2:[2]

You could add scale_x_continuous(breaks = seq(min(df$year), max(df$year), 1)) per below:

library(tidyverse)

df <- tribble(
  ~year, ~sales, ~category,
  2020, 4, "a",
  2021, 5, "a",
  2022, 5, "a",
  2020, 4, "b",
  2021, 5, "b",
  2022, 5, "b"
  ) 

df %>% 
  ggplot(aes(year, sales, fill = category)) +
  geom_area() +
  scale_x_continuous(breaks = seq(min(df$year), max(df$year), 1))

Created on 2022-04-30 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shaun_m
Solution 2 Carl