Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to visualize the top 5 values in a given column across regions

Tags:

r

dplyr

ggplot2

This is a question to what I thought would have been an easy task, but nonetheless one that I have not been able to wrap my head around.

I want to make a plot, where the top five partners for a given organisation are listed pr. regional office. Bear in mind that in my actual data there are over 700 partners 5 Regional Offices.

Suppose my data looks like this, where I have 8 values for Partners:

Partner <- c(A, B, C, D, E, F, G, A, A, B, B, C, D, E, G, G, H, I, F)
Region_Off <-c(AU, BE, CA, DK, EU, FR, GER, AU, AU , BE, BE, CA, DK, EU, 
GER, GER, HK, IR, FR)

What I have tried to do:

Top_Partners <- MY_df %>%
  count(Partner)%>%
  arrange(Partner) %>%
  arrange(n) %>%
  head(n=5) %>%
  facet_wrap(~ Region_Off)

And I have tried:

Top_Partners <- MY_df %>%
  select(Region_abb, Partner, Context)

dat2 <- as.data.frame(apply(Top_Partners, 2, function (x) sort(x, decreasing = TRUE)[1:5]))

However, I can't seem to figure out how to do this pr. regional office...

And then somehow plot this in order to make a bar chart - though I am not sure where to plot the function geom_bar in the above solution.

I hope that someone can help me move on from here.

Thank you

like image 858
BloopFloopy Avatar asked Nov 29 '25 19:11

BloopFloopy


1 Answers

It is difficult to respond to your question as your example is not reproducible. We would need a subset of MY_df and to know what the Context variable is.

Is the following data frame what you try to get?

set.seed(123)
df <- data_frame(
  Region_Off = sample(c("AU", "BE", "CA", "DK", "EU", "FR", "GER", "HK", "IR"), 500, replace = T),
  Partner = sample(LETTERS[1:8], 500, replace = T)
)

df %>% 
  group_by(Region_Off) %>% 
  count(Partner) %>% 
  arrange(desc(n)) %>% 
  slice(1:5)
like image 111
nael_kl Avatar answered Dec 01 '25 09:12

nael_kl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!