【问题标题】:How do you graph two variables from a .csv file as two lines in ggplot2?如何将 .csv 文件中的两个变量绘制为 ggplot2 中的两条线?
【发布时间】:2019-09-05 20:36:07
【问题描述】:

我已导入一个 .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"
  )

问题是我想要一条男性线和一条女性线来比较一张图表上的两条线。但我得到的实际结果是图上的一条线。

【问题讨论】:

    标签: r csv ggplot2 linear-regression linegraph


    【解决方案1】:

    您需要将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 (v0.2.1) 于 2019 年 4 月 15 日创建

    【讨论】:

    • 谢谢!如果我使用 .csv 文件,脚本将如何变化(如本文的第一部分)?完整数据介于 1900-2014 年之间。
    • 您只需将我的代码中的df 替换为数据框的名称,例如原始示例中的sex
    • this了解更多关于ggplot2
    • 你将如何调整它来制作直方图?
    • @emily123:查看我之前发布的链接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    相关资源
    最近更新 更多