如何在ggplot R中将X轴上的年份设置为整数

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

我不知道为什么,但是当我 运行 ggplot 堆叠面积图时,x 轴上的年份是双倍的,如 2012.5...。我将它们设置为整数,但仍然有这个问题。有什么解决办法吗?

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

您可以在下面添加 scale_x_continuous(breaks = seq(min(df$year), max(df$year), 1))

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

reprex package (v2.0.1)

于 2022-04-30 创建

您可以指定要与 scale_x_continuous() 一起使用的中断。

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

要使其更具动态性并根据您的数据自动选择限制,请使用:

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

如果您不想每年都显示,您可以使用 seq() 只显示第 N 年。例如。每三年:

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