barracuda317
barracuda317

Reputation: 638

Order by y-Value in Facet Plot

Consider the following data.frame

RANK_GROUP <- as.factor(c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1))
CHANNEL_CATEGORY <- as.factor(c(1,  2,  10, 15, 17, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 43, 44, 1,  2,  10, 15, 17, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 43))
CATEGORY_COUNT <- c(105, 23, 417, 10, 58, 6, 535, 211, 215, 465, 28, 273, 70, 47, 7,1,21,3,69, 14, 493, 3, 44, 3, 516, 162, 253, 516, 24, 228, 64, 59, 2, 45)

data <- data.frame(RANK_GROUP, CHANNEL_CATEGORY,CATEGORY_COUNT)

I want to make a Facet-Plot with a barplot for each distribution:

ggplot(data = data) +
  aes(x=CHANNEL_CATEGORY, y = CATEGORY_COUNT) +
  geom_bar(stat="identity", position ="dodge", colour="black") +
  facet_grid(. ~ RANK_GROUP)

Plot

How can I order the plots according to their y-value withing each facet-plot?

Upvotes: 1

Views: 180

Answers (1)

joel.wilson
joel.wilson

Reputation: 8413

took the help of cookbook,

library(dplyr)

pd <- data %>%
      group_by(RANK_GROUP) %>%
      top_n(nrow(data), abs(CATEGORY_COUNT)) %>% 
      ungroup() %>%
      arrange(RANK_GROUP, CATEGORY_COUNT) %>%
      mutate(order = row_number())

 pd$order <- as.factor(pd$order)

ggplot(data = pd) +
  aes(x=order, y = CATEGORY_COUNT) +
  geom_bar(stat="identity", position ="dodge", colour="black") +
  facet_grid(. ~ RANK_GROUP)+
  scale_x_discrete(labels = CHANNEL_CATEGORY , breaks = order)+
 theme(axis.text.x = element_text(angle = 60, hjust = .5, size = 8)) +
 labs(x="Channel")

enter image description here

Upvotes: 1

Related Questions