我的ggplot图表首先显示2018年,然后显示2017年数据。我想重新排序

时间:2018-09-06 05:56:24

标签: r ggplot2

plot

我有2017年9月至2018年8月的数据。

但是,当我通过ggplot显示它时,它的绘制时间是从2018年1月到2018年8月,然后是2017年9月-12月。我希望首先获得2017年的数据。

这是我使用的代码:

ggplot(data = p3, 
       aes(x = month, 
           y = percentage)) +
  geom_bar(aes(y = percentage*100), stat = "identity")+
  geom_text(aes(y = percentage, label = formattable::percent(percentage)), 
            vjust = 1.5, colour="red")

1 个答案:

答案 0 :(得分:2)

一种解决方案是将month列转换为日期,方法是将“ 01 /”放在前面(每个月的第一天)。然后,您可以使用scale_x_date

library(dplyr)
library(ggplot2)

p3 %>% 
  mutate(Date = as.Date(paste0("01/", month), "%d/%m/%Y")) %>% 
  ggplot(aes(Date, percentage)) + 
    geom_col() + 
    geom_text(aes(y = percentage, 
                  label = formattable::percent(percentage)), 
              vjust = 1.5, 
              colour = "red") +
    scale_x_date(date_breaks = "1 month", 
                 date_labels = "%m/%Y")