floss
floss

Reputation: 2773

Using R how to plot and color with multiple facet

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?

What did I do?

    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?

Upvotes: 1

Views: 153

Answers (1)

M--
M--

Reputation: 28826

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)

Upvotes: 1

Related Questions