简体   繁体   English

按累计天数对 geom_tile plot 的 y 轴进行排序

[英]ordering y axis of geom_tile plot by cumulative sum of days

I have a dataset with 4 columns client , date , sales and scale .我有一个包含 4 列clientdatesalesscale的数据集。

I am trying figure it ou how to to order the y axis ( client ) on a geom_tile plot not based on the default decreasing order of the levels but instead on the cumulative sum of each client for all days.我试图弄清楚如何在 geom_tile plot 上排序 y 轴( client ),而不是基于级别的默认降序,而是基于每个客户端所有天的累积总和。

The code bellow is an example.下面的代码就是一个例子。 The client are ordered 5,4,3,2,1 but I need instead ordered based on the sales of all days.客户订购了 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,300,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)

Appreciate any help感谢任何帮助

Maybe a quick fix like this?也许像这样的快速修复?

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,300,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)

Personally, I prefer the set the factor levels, in the data.frame, and plot就个人而言,我更喜欢在 data.frame 和 plot 中设置因子水平

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

df %>% mutate(client = factor(client,levels=o)) %>%
ggplot(.,aes(x=date,y=client,fill=escale)) + 
geom_tile(colour="white",size=0.25)

Both will give this:两者都会给出:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM