x轴上的月份,以整数为单位

问题描述 投票:0回答:1

我想将x轴上的数字转换为月份,我以某种方式成功了,但是我希望月份按时间顺序而不是字母顺序排列。

我使用了以下代码:

temp %>% 
  ggplot(aes(month.abb[MoSold], fill = SalePrice)) + 
  geom_bar() +
  scale_y_continuous(labels = number) +
  xlab("Month") +
  theme_bw()

上面的代码正在产生以下图形months in alphabetical order.

相反,我希望图形看起来像名称而不是数字graph with chronological order without month name

r ggplot2 geom-bar ggplotly geom-text
1个回答
0
投票

month.abb[]产生的字符,除了字母之外,R中的字符没有固有的顺序,这是ggplot显示它们的方式。

ggplot(data = data.frame(
  months = month.abb[1:10],
  num = 1:10),
  aes(months, num)) +
  geom_col()

enter image description here

要按预期顺序查看它们,至少有3个选项:

1)将month.abb转换为factor数据类型,可以具有指定的顺序。

# Convert months to factors using `forcats` package
ggplot(data = data.frame(
  months = forcats::fct_reorder(month.abb[1:10], 1:10),
  num = 1:10),
  aes(months, num)) +
  geom_col()

# Convert months to factors using base R 
ggplot(data = data.frame(
  months = factor(1:10, labels = month.abb[1:10]),
  num = 1:10),
  aes(months, num)) +
  geom_col()

enter image description here

2)或者,您也可以交替使用数字轴,其自定义标签反映您想要的内容:

ggplot(data = data.frame(
  month_num = 1:10,
  num = 1:10),
  aes(month_num, num)) +
  geom_col() +
  scale_x_continuous(labels = function(x) month.abb[x])

3)也许最简单的是,您可以使用Date或POSIXct数据类型。

ggplot(data = data.frame(
  month = seq.Date(as.Date("2019-01-01"), as.Date("2019-10-01"), by = "month"),
  num = 1:10),
  aes(month, num)) +
  geom_col() +
  scale_x_date(date_breaks = "1 month", 
               minor_breaks = NULL, date_labels = "%b")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.