Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R在ggplot2中按年份然后按月排序_R_Ggplot2 - Fatal编程技术网

R在ggplot2中按年份然后按月排序

R在ggplot2中按年份然后按月排序,r,ggplot2,R,Ggplot2,如果你看一下我的df\u summary\u mo表格,它很好地按年份排列,然后按月份排列 year month total <fctr> <chr> <dbl> 1 2017 10 11.02006 2 2017 11 16.62367 3 2017 12 14.84555 4 2018 01 14.61277 5 2018 02 14.06558 6 2018

如果你看一下我的df\u summary\u mo表格,它很好地按年份排列,然后按月份排列

     year month    total
   <fctr> <chr>    <dbl>
 1   2017    10 11.02006
 2   2017    11 16.62367
 3   2017    12 14.84555
 4   2018    01 14.61277
 5   2018    02 14.06558
 6   2018    03 15.73514
 7   2018    04 14.51999
 8   2018    05 14.33848
 9   2018    06 13.49925
10   2018    07 14.04433
11   2018    08  3.88255
年-月合计
1   2017    10 11.02006
2   2017    11 16.62367
3   2017    12 14.84555
4   2018    01 14.61277
5   2018    02 14.06558
6   2018    03 15.73514
7   2018    04 14.51999
8   2018    05 14.33848
9   2018    06 13.49925
10   2018    07 14.04433
11   2018    08  3.88255
默认情况下,ggplot2以将月份按数字顺序排列(1,2,3,4…)的格式对该特定图形(下面的代码)进行排序。我如何让图表将2017个月放在2018个月之前?我把重新排序的论点弄得乱七八糟,但似乎没有什么帮助

library(dplyr)
library(lubridate)

df <- data.frame(date = today() + days(1:300), value = runif(300))

df_summary_mo <- df %>%
mutate(year = format(date, "%Y"), month = format(date, "%m")) %>%
group_by(year, month) %>%
summarise(total = sum(value))

ggplot(df_summary_mo, aes(month, total, fill=year, reorder(year,month))) + geom_col()
库(dplyr)
图书馆(lubridate)
df%
分组单位(年、月)%>%
汇总(总额=总和(价值))
ggplot(df_汇总图、aes(月、总计、填充=年、再订购(年、月))+geom_col()

我将定义
yearmon
以便订单自动运行

df_summary_mo <- df %>%
  mutate(year = format(date, "%Y"), yearmon = format(date, "%Y-%m")) %>%
  group_by(year, yearmon) %>%
  summarise(total = sum(value))

ggplot(df_summary_mo, aes(yearmon, total, fill=year)) + geom_col()
df\u摘要\u mo%
变异(年=格式(日期,“%Y”)、年月=格式(日期,“%Y-%m”))%>%
组别(年,一月)%>%
汇总(总额=总和(价值))
ggplot(df_汇总,aes(一年一次,总计,填充=一年))+geom_col()

除了@AndrewGustar给出的答案之外,x轴标签可以通过使用
element\u text()
ggplot()
调用来旋转,比如,
ggplot(df\u summary\u mo,aes(yearmon,total,fill=year))+geom\u col()+主题(axis.text.x=element\u text(angle=65,hjust=1))
。这样,
x轴
标签就不会重叠。