gpt4 book ai didi

r - 如何使用ggplot在x轴上只显示年份

转载 作者:行者123 更新时间:2023-12-05 02:59:10 24 4
gpt4 key购买 nike

我希望我的多折线图在 x 轴上仅显示年份(而不是年份和月份)。我尝试使用 "%Y" 格式化“年”,但 df2 显示日、月和年。

library(tidyverse)
theme_set(theme_minimal())

df <- tibble(
year = as.character(c(2015, 2016)),
v1 = c(3,10),
v2 = c(7,18))

df$year <- as.Date(df$year, "%Y")
format(df$year, "%Y")
#> [1] "2015" "2016"

df2 <- df %>%
gather(key = "variable", value = "value", -year)

ggplot(df2, aes(x = year, y = value)) +
geom_line(aes(color = variable, linetype = variable)) +
scale_color_manual(values = c("darkred", "steelblue"))

最佳答案

使用 lubridate 包。

您可以使用 scale_x_date,因为您的日期是 2015 年和 2016 年的 10 月,所以我将日期移动了 9 个月以在图表中同时显示 2015 年和 2016 年。

library(lubridate)
df2 <- df %>%
gather(key = "variable", value = "value", -year) %>%
mutate(year = year - months(9))

ggplot(df2, aes(x = year, y = value)) +
geom_line(aes(color = variable, linetype = variable)) +
scale_color_manual(values = c("darkred", "steelblue")) +
scale_x_date(date_breaks = "1 year",date_labels = "%Y")

另一种方法是从日期列中提取年份作为整数,并使用 year(integer) 来绘制,您还需要指定 breaks。

df2 <- df %>%
gather(key = "variable", value = "value", -year) %>%
mutate(year = lubridate::year(year))

ggplot(df2, aes(x = year, y = value)) +
geom_line(aes(color = variable, linetype = variable)) +
scale_color_manual(values = c("darkred", "steelblue")) +
scale_x_continuous(breaks = c(2015,2016))

两者的结果相同。

enter image description here

关于r - 如何使用ggplot在x轴上只显示年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58240030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com