R ggplot vs barplot 2

Viewed 29

I am trying to replicate the stacked bar chart built via ggplot() into a chart that uses barplot(). My code is below. My problem is that barplot() produces not a stacked chart. What do I do in a wrong way here? Thanks!

Data is accessible at the following link.

# link to the data: https://drive.google.com/file/d/16FQ7APc0r1IYS_geMdeBRoMiUMaF01t3/view?usp=sharing
df <- read.csv("US Sectoral Balances 3.csv")

# ggplot()
df %>%
  # Plotting the data via ggplot2()
  ggplot(aes(x = TimePeriod, y = DataValue_per_GDP, color = Sectors, fill = Sectors)) + 
  geom_col(aes(fill = Sectors), position = "stack", width = 1) +
  scale_y_continuous(labels = percent, 
                     sec.axis = sec_axis(~., name = "", labels = percent)) +
  scale_x_discrete(name=NULL, breaks = brks) +
  scale_fill_manual(values=c("#FF3399", "#3399FF", "#66CC99","#0022CC","#11AA00")) +
  scale_color_manual(values=c("#FF3399", "#3399FF", "#66CC99","#0022CC","#11AA00")) +
  guides(fill = guide_legend(title.theme = 
                               element_text(size = 9, face = "bold", 
                                            colour = "black", angle = 0))) +
  labs(x ="", y = "(% of GDP)", 
       subtitle = "Three-sector breakdown",
       title = paste0("U.S. Sectoral Balances", 
                      " through ", year(max(df$date))," ",quarters(max(df$date))),
       caption = paste0("\nNote: data is from the BEA's Table 5.1. Saving and Investment by Sector.",
                        "\n\nSource: BEA.")) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, size = 10),
        plot.caption = element_text(hjust = 0, size = 8))

# barplot()
l <- min(
  length(df[substr(df$Sectors,1,1)=="A",]$DataValue_per_GDP),
  length(df[substr(df$Sectors,1,1)=="B",]$DataValue_per_GDP),
  length(df[substr(df$Sectors,1,1)=="C",]$DataValue_per_GDP)
)
bar_data <- matrix(data = rbind(df[substr(df$Sectors,1,1)=="A",]$DataValue_per_GDP*100,
                                df[substr(df$Sectors,1,1)=="B",]$DataValue_per_GDP*100,
                                df[substr(df$Sectors,1,1)=="C",]$DataValue_per_GDP*100), 
                   nrow = 3, ncol = l)

colnames(bar_data) <- df[substr(df$Sectors,1,1)=="A",]$TimePeriod[1:l]
rownames(bar_data) <- c("A. General government","B. Private","C. External")

barplot(bar_data, col=c("red","blue","green"), beside = FALSE)
barplot(bar_data, col=c("red","blue","green"), beside = TRUE)

enter image description here

0 Answers
Related