TransWikia.com

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

Stack Overflow Asked by user13953317 on December 20, 2021

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?

2 Answers

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

Answered by akrun on December 20, 2021

How about

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

?

Answered by Ben Bolker on December 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP