简体   繁体   中英

How to plot several columns on the same line chart in R?

my data is

year female male unknown
1929   0     50     0
1930   2     70     7
1931   0     400    1
1932  20     40     15
1933  25     120    0

I need to create a simple line chart with 3 lines where I can see gender changes over years.

I have tried something like

data <- melt(data,  id.vars = 'year', variable.name = 'Gender')

ggplot(data, aes(year, value)) + geom_line(aes(colour = Gender))

but it shows me an empty chart and a comment

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

  1. How can I create a chart where I will have three lines, one for each gender?

  2. Also, my date is bigger than this one, it contains 92 years so when I plot something, I get a huge mess of years on the x-axis

在此处输入图像描述

Is there a way to somehow fix it?

How about

matplot(data$year,data[,-1], type="l")

?

With tidyverse , we pivot to 'long' format, specify the group and color with the column name 'name' column (default naming)

library(dplyr)
library(tidyr)
library(ggplot2)
data %>%
    pivot_longer(cols = -year) %>%
    ggplot(aes(x = year, y = value, group = name, color = name)) + 
      geom_line()

在此处输入图像描述

data

data <- structure(list(year = 1929:1933, female = c(0L, 2L, 0L, 20L, 
25L), male = c(50L, 70L, 400L, 40L, 120L), unknown = c(0L, 7L, 
1L, 15L, 0L)), class = "data.frame", row.names = c(NA, -5L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM