I have a simple data where fields are year, the share of agri, industry, and services. I need to draw a stacked bar chart in R for these for 3 years.
Here is a guess at how your data are arranged and how to change them to make a stacked bar chart with ggplot. If you need more help, please post the output of running the dput() function on your data frame. If your data frame is named DF, run
dput(DF)
and post the output here.
DF <- data.frame(Year = c(2020,2021,2022),
Agri = c(15, 13, 14),
Industry = c(40,45,46),
Services = c(45, 42, 40))
DF
#> Year Agri Industry Services
#> 1 2020 15 40 45
#> 2 2021 13 45 42
#> 3 2022 14 46 40
library(tidyr)
library(ggplot2)
DF_long <- DF |> pivot_longer(cols = Agri:Services, names_to = "Sector",
values_to = "Share")
DF_long
#> # A tibble: 9 × 3
#> Year Sector Share
#> <dbl> <chr> <dbl>
#> 1 2020 Agri 15
#> 2 2020 Industry 40
#> 3 2020 Services 45
#> 4 2021 Agri 13
#> 5 2021 Industry 45
#> 6 2021 Services 42
#> 7 2022 Agri 14
#> 8 2022 Industry 46
#> 9 2022 Services 40
ggplot(DF_long, aes(x = Year, y = Share, fill = Sector)) + geom_col() +
labs(y = "Share of Economy", title = "Share of Economy by Year")
Created on 2023-09-08 with reprex v2.0.2
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.