首页 > 解决方案 > 从R中的频率表制作折线图

问题描述

我制作了一个频率表来查看 4 年期间种族类别的百分比。使用以下代码:

race <- table(crc$raceeth, crc$year)
perrace <- prop.table(race, 2)

我创建了一个如下所示的表:

                      2014      2015      2016      2017      2018
  Other              0.1032609 0.1433232 0.1335762 0.1141788 0.1285297
  Latino             0.3913043 0.3339548 0.2173649 0.2321011 0.2434275
  non-hispanic black 0.3695652 0.3087858 0.3995143 0.4361254 0.4634859
  non-hispanic white 0.1358696 0.2139361 0.2495446 0.2175948 0.1645570

现在我想创建一个折线图,在 x 轴上有年份,在 y 轴上有每个种族/民族的线条,但我不知道从这里去哪里

标签: rgraphgraphics

解决方案


这是一种tidyverse方法:

library(tidyverse)
df %>%
    rownames_to_column("Group") %>%
    gather(x, y, -Group) %>%
    mutate(x = as.Date(gsub("X", "", x), format = "%Y")) %>%
    ggplot(aes(x, y, colour = Group)) +
    geom_line()

在此处输入图像描述


样本数据

df <- read.table(text =
    "                    2014      2015      2016      2017      2018
  'Other'              0.1032609 0.1433232 0.1335762 0.1141788 0.1285297
  'Latino'             0.3913043 0.3339548 0.2173649 0.2321011 0.2434275
  'non-hispanic black' 0.3695652 0.3087858 0.3995143 0.4361254 0.4634859
  'non-hispanic white' 0.1358696 0.2139361 0.2495446 0.2175948 0.1645570", header = T, row.names = 1);

推荐阅读