【问题标题】:can't convert month number to month date in R [duplicate]无法在 R 中将月份数转换为月份日期 [重复]
【发布时间】:2022-08-09 15:24:35
【问题描述】:

我想在西班牙创建一个具有不同树类型的 ggplot。

我用了那个代码

library(dplyr)
library(reshape)
set.seed(123)
library(ggplot2)
library(tidyr)
df_long <- pivot_longer(df7, 
                        cols = c(Birch, Palm, Oak), 
                        values_to = \"m3\",
                        names_to = \"Trees\")


# Plot
ggplot(df_long,
       aes(
         x = Month,
         y = Integral,
         color = Trees
       )) +
  geom_line() +
  ggtitle(\"trees in Spain\") +
  xlab(\"Month\") +   scale_x_continuous(breaks = seq(1, 12, by = 1), limits = c(1,12)) +
  ylab(\" m3\") 

但不幸的是,没有显示月份名称,只是数字,但我想要月份名称

标签: r ggplot2


【解决方案1】:

如果您的月份是整数,您可以使用内置常量 month.abbmonth.name

library(dplyr)
df  <- data.frame(month_nums = 1:12)

df  |> 
    mutate(
        month_abb = month.abb[month_nums],
        month_full = month.name[month_nums]
    )
#    MONTH month_abb month_full
# 1      1       Jan    January
# 2      2       Feb   February
# 3      3       Mar      March
# 4      4       Apr      April
# 5      5       May        May
# 6      6       Jun       June
# 7      7       Jul       July
# 8      8       Aug     August
# 9      9       Sep  September
# 10    10       Oct    October
# 11    11       Nov   November
# 12    12       Dec   December

如果它们是日期,您可以使用format()

df  <- data.frame(
    month = seq(from = as.Date("2020-01-01"), to = as.Date("2020-12-31"), by = "month")
)

df  |>
    mutate(
        month_abb = format(month, "%b"), 
        month_full = format(month, "%B")
    )
#         month month_abb month_full
# 1  2020-01-01       Jan    January
# 2  2020-02-01       Feb   February
# 3  2020-03-01       Mar      March
# 4  2020-04-01       Apr      April
# 5  2020-05-01       May        May
# 6  2020-06-01       Jun       June
# 7  2020-07-01       Jul       July
# 8  2020-08-01       Aug     August
# 9  2020-09-01       Sep  September
# 10 2020-10-01       Oct    October
# 11 2020-11-01       Nov   November
# 12 2020-12-01       Dec   December

【讨论】:

    猜你喜欢
    • 2014-12-29
    • 2017-01-27
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多