1

My R dataset (migration) looks like this:

date    gender  UK      USA      Canada      Mexico
1990    M       4.2     6.3      4.0         5.1
1990    F       5.2     4.3      6.0         4.1
1991    M       3.2     5.3      5.0         7.1
1991    F       4.2     5.3      4.0         4.1
1992    M       3.2     3.3      2.0         5.1
1992    F       6.2     6.3      4.0         3.1

What do I want to do?

  • I want to create a plot showing the trend line by year of all countries.
  • I want to color by gender
  • Facet by countries

What did I do?

  • I produced the following code
    ggplot(migration,
       aes(date,gender, color=gender)) +
    geom_point() + 
    facet_wrap(UK~USA~Canada~Mexico)

However, it does not work. Please kindly help me solve this?

0

1 Answer 1

1
library(ggplot2)
library(tidyr)

migl <- gather(data = migration, country, value, -c(date, gender))

ggplot(data = migl,
       aes(x = date, y = value, color = gender)) +
  geom_point(size=2) + 
  geom_smooth()+
  facet_wrap(~country)

Data:

migration <- read.table(text="date    gender  UK      USA      Canada      Mexico
                              1990    M       4.2     6.3      4.0         5.1
                              1990    F       5.2     4.3      6.0         4.1
                              1991    M       3.2     5.3      5.0         7.1
                              1991    F       4.2     5.3      4.0         4.1
                              1992    M       3.2     3.3      2.0         5.1
                              1992    F       6.2     6.3      4.0         3.1", header=T)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for composing the answer. How did it know the variables were country?
@floss I defined its name within gather. I could call it key or variable.

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.