如何将.csv文件中的两个变量图形化为ggplot2中的两行?

问题描述 投票:1回答:1

我导入了一个.csv文件,并在线图上绘制了我的数据点。但我试图比较男性和女性的预期寿命,但我无法弄清楚如何为男性和女性绘制一条线。

以下是我数据的一部分示例(ALE代表平均预期寿命)。

Year    Sex ALE
1900    Female  48.3
1900    Male    46.6
1901    Female  50.6
1901    Male    48
1902    Female  53.4
1902    Male    50.2
1903    Female  52
1903    Male    49.5
1904    Female  49.1
1904    Male    46.6
1905    Female  50.2
1905    Male    47.6

这是我到目前为止的代码。最终,我将把我的工作放到.rmd文件中。

library(ggplot2) # call up ggplot2
library(RColorBrewer) # call up rcolorbrewer palette
options(scipen = 999) # remove scientific notation
sex <- read.csv("~/Big Data IBP/Life expectancy_sex.csv") # data focusing on life expectancy comparing sex. #male v. female
# run test to see how year of death has changed over the years
ggplot(data = sex, aes(x = Year, y = ALE)) +
  geom_line(linetype = "solid", col = "Blue", size = 0.5, arrow = arrow()) +
  labs(
    title = "Average Life Expectancy Based on Sex",
    subtitle = "1900-2014", x = "Year", y = "Age at Death"
  )

问题是我希望男性有一行,女性有一行比较一个图上的2行。但是我的实际结果是图表上的一行。

r csv ggplot2 linear-regression linegraph
1个回答
0
投票

你需要将groupcolorlinetype映射到aes

library(ggplot2) # call up ggplot2
options(scipen = 999) # remove scientific notation

df <- read.table(text = "Year    Sex ALE
1900    Female  48.3
1900    Male    46.6
1901    Female  50.6
1901    Male    48
1902    Female  53.4
1902    Male    50.2
1903    Female  52
1903    Male    49.5
1904    Female  49.1
1904    Male    46.6
1905    Female  50.2
1905    Male    47.6",
                 header = TRUE, stringsAsFactors = FALSE)
# run test to see how year of death has changed over the years
ggplot(data = df, aes(x = Year, y = ALE, 
                      group = Sex, color = Sex, linetype = Sex)) +
  geom_line(size = 0.5, arrow = arrow()) +
  labs(
    title = "Average Life Expectancy Based on Sex",
    subtitle = "1900-2014", x = "Year", y = "Age at Death"
  ) +
  scale_color_brewer(palette = "Dark2") +
  theme_classic(base_size = 16)

reprex package创建于2019-04-15(v0.2.1)

© www.soinside.com 2019 - 2024. All rights reserved.