0

How to order the bar chart when using weight to calculate sum of b for every different a?

I also tried +scale_x_discrete(limits = data$b) from Ordering graph by weight value but did not working(pic2).

data
   a b
1  A 1
2  B 2
3  A 3
4  B 1
5  C 2
6  A 3
7  B 4
8  B 5
9  B 1
10 C 1

ggplot(data,aes(a,weight=b)) + geom_bar()

enter image description here

ggplot(data,aes(a,weight=b)) + geom_bar() + scale_x_discrete(limits = data$b)

Warning message: Removed 10 rows containing non-finite values (stat_count).

enter image description here

Data:

a <- c("A","B","A","B","C","A","B","B","B","C")
b <- c(2,3,4,2,3,4,5,6,2,2)
data <- cbind(a,b)
data <- as.data.frame(data)
data$b <- as.numeric(data$b)
camille
  • 16,432
  • 18
  • 38
  • 60
Menkot
  • 694
  • 1
  • 6
  • 17

1 Answers1

1

Here's an approach using dplyr and forcats to get the total weighted count for each a and to reorder it as a factor based on that total.

library(dplyr)
data %>%
  add_count(a, wt = b) %>%
  mutate(a = forcats::fct_reorder(a, -n)) %>%
  ggplot(aes(a, n)) + 
  geom_col()  # equivalent to geom_bar(stat = "identity")

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53