使用R如何绘制和多面着色 [英] Using R how to plot and color with multiple facet

查看:59
本文介绍了使用R如何绘制和多面着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 R 数据集( migration )如下所示:

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

我想做什么?

  • 我想创建一个图,显示所有国家/地区的年份趋势线.
  • 我想用 gender
  • color
  • 国家
  • I want to create a plot showing the trend line by year of all countries.
  • I want to color by gender
  • Facet by countries

我做了什么?

  • 我产生了以下代码
    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?

推荐答案

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)

这篇关于使用R如何绘制和多面着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆