How do you create a bar chart that consist the sum of mutiple column?

Hi everyone,

I am trying to make a bar chart to consist of mutiple bar that are a sum of different column. But it just show me an empty plot. I am not sure how to do it and I try to find everywhere I can. I am new to this so please advice.

Thank you very much.

Below are my code.

demographic_data %>%
ggplot() +
geom_bar(aes(x = sum(demographic_data$Mntwines))) +
geom_bar(aes(x = sum(demographic_data$MntMeatProducts))) +
geom_bar(aes(x = sum(demographic_data$MntSweetProducts)))

I am guessing you need to do something like the following. You did not provide any data so I invented a small set. I first reshaped the data so that the type of product is listed in one column and another column contains all of the values. This is typically the preferred arrangement for plotting with ggplot. I then summed over each product and then plotted that result. I put in extra print steps to show what each step does.

demographic_data <- data.frame(MntWines=c(4,7),MntMeatProducts=c(4,3),
                               MntSweetProducts=c(6,5))
demographic_data
#>   MntWines MntMeatProducts MntSweetProducts
#> 1        4               4                6
#> 2        7               3                5

library(tidyr)
library(dplyr)
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.5
DF_Long <- demographic_data %>% pivot_longer(cols = MntWines:MntSweetProducts,
                                             names_to="Product",values_to="Value")
DF_Long
#> # A tibble: 6 x 2
#>   Product          Value
#>   <chr>            <dbl>
#> 1 MntWines             4
#> 2 MntMeatProducts      4
#> 3 MntSweetProducts     6
#> 4 MntWines             7
#> 5 MntMeatProducts      3
#> 6 MntSweetProducts     5

DF_Sums <- DF_Long %>% group_by(Product) %>% summarize(Total=sum(Value))
#> `summarise()` ungrouping output (override with `.groups` argument)
DF_Sums
#> # A tibble: 3 x 2
#>   Product          Total
#>   <chr>            <dbl>
#> 1 MntMeatProducts      7
#> 2 MntSweetProducts    11
#> 3 MntWines            11
ggplot(DF_Sums,aes(x=Product,y=Total))+geom_col(fill="steelblue")

Created on 2021-09-11 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.