简体   繁体   English

plot R 中同一折线图上的几列如何?

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

my data is我的data

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.我需要创建一个简单的折线图,其中包含 3 条线,我可以在其中看到多年来的性别变化。

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. geom_path:每组仅包含一个观察值。 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另外,我的日期比这个大,它包含 92 年,所以当我 plot 某事时,我在 x 轴上得到了一大堆年份

在此处输入图像描述

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)tidyverse ,我们 pivot 为 'long' 格式,用列名 'name' 列指定groupcolor (默认命名)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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