通过天的累积总和对geom_tile图的y轴排序

我有一个包含4列clientdatesalesscale的数据集。

我正在尝试解决它或如何在geom_tile图上排序y轴(client)的过程,而不是基于级别的默认递减顺序,而是基于每个客户在整天内的累计总和。

下面的代码是一个示例。客户被订购了5,4,3,2,1,但我需要根据全天的销售量订购。

data.frame(client=seq(1:5),date=Sys.Date()-0:05,sales=rnorm(30,300,100)) %>% mutate_if(is.numeric,round,0) %>% mutate(escale=cut(sales,breaks=c(0,100,200,1000),labels=c("0-100","100-200","200-300","+300"))) %>% ggplot(.,aes(x=date,y=client,fill=escale)) + geom_tile(colour="white",size=0.25)

感谢任何帮助

lili19890701 回答:通过天的累积总和对geom_tile图的y轴排序

也许可以这样快速解决?

df <- data.frame(client=seq(1:5),date=Sys.Date()-0:05,sales=rnorm(30,300,100)) %>% 
mutate_if(is.numeric,round,0) %>% 
mutate(escale=cut(sales,breaks=c(0,100,200,1000),labels=c("0-100","100-200","200-300","+300")))

# we get the order according to total sales
o <- names(sort(tapply(df$sales,df$client,sum)))

ggplot(df,aes(x=date,y=client,fill=escale)) + 
geom_tile(colour="white",size=0.25)+
# just manually set the y-axis here
scale_y_discrete(limits=o)

我个人更喜欢在data.frame中设置因子级别并绘制

# we get the order according to total sales
o <- names(sort(tapply(df$sales,sum)))

df %>% mutate(client = factor(client,levels=o)) %>%
ggplot(.,size=0.25)

两者都会给这个:

enter image description here

本文链接:https://www.f2er.com/3108387.html

大家都在问