S O
S O

Reputation: 11

from matrix to ggplot

I kind of new with R - and i would like to improve my relationship ;-)

I have a matrix called "gender.years") which looks so:

           2000 2001 2002 2003 
 masculin   162  149    0    0    
 feminin    289  345    0    0    
 unknown      0    0    0    0 

So, colnames are years (strings) and rows are the amount of values for masculin, feminin, unknown.

ggplot(data=as.data.frame(gender.years), 
       mapping = aes(x=years, y=gender, group=gender )
       )
      +geom_line()
      +geom_point()

if I test "as.data.frame(gender.years)" i got a nice output. I mean, R shows it as a dataframe

    2000   2001 ... 
    <dbl>  <dbl>... 

masculin 162 149 ... feminin 289 345 ... unknown 0 0...

What i believe to understand is: my ggplot idea is quite not fitting. I'd appreciate a lot, if you could help me to have a better contact with gg. I want to work on me.

Best, Sebastian

Upvotes: 1

Views: 66

Answers (1)

stefan
stefan

Reputation: 123783

The issue is that even after converting your matrix to a dataframe there is no column gender (gender is the rownames) and no column years (which are spread over multiple columns). So you have to add the rownames as a variable to your data.frame and bring your data in the right shape before plotting:

gender.years <- structure(c(162L, 289L, 0L, 149L, 345L, 0L, 0L, 0L, 0L, 0L, 0L, 
                 0L), .Dim = 3:4, .Dimnames = list(c("masculin", "feminin", "unknown"
                 ), c("2000", "2001", "2002", "2003")))

library(ggplot2)
library(dplyr)
library(tidyr)
library(tibble)

as.data.frame(gender.years) %>% 
  rownames_to_column(var = "gender") %>% 
  pivot_longer(-gender, names_to = "years") %>% 
  ggplot(mapping = aes(x=years, y=value, group=gender, color=gender)) +
  geom_line() + 
  geom_point()

Upvotes: 1

Related Questions