user13953317
user13953317

Reputation: 35

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

enter image description here

Is there a way to somehow fix it?

Upvotes: 2

Views: 519

Answers (2)

akrun
akrun

Reputation: 886938

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()

enter image description here

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))

Upvotes: 2

Ben Bolker
Ben Bolker

Reputation: 226057

How about

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

?

Upvotes: 2

Related Questions