0

I want to generate from dd1 a plot as below using just the base R function barplot such that grouping is by year for each country. I can do it using ggplot but can't identify the proper way to get it to work using barplot.

enter image description here

Input dataframe:

dd1 <- data.frame("yr" = c(2001,2002,2001,2002), "country" = c("Chile","China","Chile","China"), "trade"=c(1200,2400,2500,5000))

1 Answer 1

2

Simply turn your dataframe into a grouped matrix using tapply by yr and country:

graph_data <- tapply(dd1$trade, list(dd1$yr, dd1$country), sum)

barplot(graph_data, beside=TRUE, col=rainbow(3),
        legend=rownames(graph_data), ylim=c(0,30000000), ylab="Trade", xlab="Country")

To demonstrate with a larger dataframe of Asian countries with random data:

asia_countries <- c("China", "India", "Indonesia", "Pakistan", "Bangladesh", "Japan", "Philippines", "Viet Nam", 
                    "Iran", "Turkey", "Thailand", "Myanmar", "South Korea", "Iraq", "Afghanistan", 
                    "Saudi Arabia", "Uzbekistan", "Malaysia", "Nepal", "Yemen", "North Korea", 
                    "Sri Lanka", "Kazakhstan", "Syria", "Cambodia", "Azerbaijan", "Jordan", 
                    "United Arab Emirates", "Tajikistan", "Israel", "Laos", "Kyrgyzstan", "Lebanon", 
                    "Turkmenistan", "Singapore", "State of Palestine", "Oman", "Kuwait", 
                    "Georgia", "Mongolia", "Armenia", "Qatar", "Bahrain", "Timor-Leste", "Cyprus", 
                    "Bhutan", "Maldives", "Brunei")

set.seed(662018)
dd1 <- transform(expand.grid("yr" = c(2014:2016),
                             "country" = asia_countries), 
                 "trade"= sample(2000:20000, 144, replace=TRUE))

graph_data <- tapply(dd1$trade, list(dd1$yr, dd1$country), sum)

# PASS LENGTH OF LEGEND SERIES (I.E. YEARS) INTO rainbow(n)
barplot(graph_data, beside=TRUE, col=rainbow(3), legend=rownames(graph_data), 
        ylim=c(0,20000), ylab="Trade", xlab="Country")

Bar Plot Output

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.