Here is data of sales by year and model. Now I wan to rank/order these models by following:
Models has to be ordered from top to down according to their sales in each year. For example, E had the biggest sales in 2015, so it must the on the TOP, while in 2017 H must be on the TOP.
Moreover, I need to keep model J always on the bottom regardless its share.
library(dplyr)
library(ggplot2)
df <- data.frame (model = c("A","B","C","D","E","F","G","H","I","J","A","B","C","D","E","F","G","H","I","J","A","B","C","D","E","F","G","H","I","J","A","B","C","D","E","F","G","H","I","J"),
Year = c(2015,2015,2015,2015,2015,2015,2015,2015,2015,2015,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2018,2018,2018,2018,2018,2018,2018,2018,2018,2018),
sales = c(450,678,456,344,984,456,234,244,655,789,234,567,234,567,232,900,1005,1900,450,345,567,235,456,345,144,333,555,777,111,444,222,223,445,776,331,788,980,1003,456,434))
df %>%
group_by(Year) %>%
mutate(Share = sales / sum(sales)) %>%
mutate_at(vars(Share), funs(round(., 4))) %>%
ggplot(aes(fill=model, y=Share, x=Year))+
scale_x_continuous(breaks=seq(min(df$Year),max(df$Year),2))+
geom_col(position="fill", width = 1, color = "white") +
geom_text(aes(label = scales::percent(Share, accuracy = 0.1)),
position = position_fill(vjust = 0.50),
color = "black",size = 2) +
scale_y_continuous(labels = scales::percent)