繁体   English   中英

如何从数据子集中创建基础 R 分散 Plot

[英]How to make a base R scatter Plot from a data subset

我正在使用 R 基础绘图。 我需要对两列进行子集化,其中一列是性别=女性,另一列是 Measure.Variables=预期寿命。 由于 Measure.Variables 列有两个值“预期寿命”和“死亡率”。

此外,我正在尝试手动设置 y 和 x 轴的中断和限制,但我无法这样做。 我附上了一张我想添加的休息和限制的图片。

图形 图片

你能帮我解决这个问题吗? 我想将 y 轴的中断设置为 break=c(30,40,50,60,70,80),将 x 轴的中断设置为 break=c(1900,1920,1940,1960,1980,2000)。 无论数据是否可用,我都希望出现这些限制。

我正在使用以下代码,当我在子集语句中添加第二个条件时,它给了我一个错误。 否则,它可以在没有 Measure.Variables==Life Expectancy 命令的情况下正常工作。

以下是output的数据

structure(list(Measure.Variables = c("Life Expectancy", "Life Expectancy", 
"Life Expectancy", "Mortality", "Life Expectancy", "Life Expectancy"
), Race = c("All Races", "All Races", "All Races", "All Races", 
"All Races", "All Races"), Sex = c("Both Sexes", "Both Sexes", 
"Both Sexes", "Both Sexes", "Both Sexes", "Both Sexes"), Year = 1900:1905, 
    Average.Life.Expectancy = c(47.3, 49.1, 51.5, 50.5, 47.6, 
    48.7), Mortality = c(NA_real_, NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_)), row.names = c(NA, 6L), class = "data.frame")

我正在使用以下代码

with(subset(LF, Sex == "Male", Measure.Variables == "Life Expectancy"), 
     plot(Year, Average.Life.Expectancy, col="red", pch=17,
          main="Male Life Expectancy", ylab="Life Expectancy"))

为响应阿黛尔而编辑,y 值仍未显示。 在阿黛尔的建议下看这张图

更容易设置data=参数,并在subset中使用&单独选择。 对于轴自定义,使用xaxt='n'yaxt='n'停用轴文本,并使用axis()构建自己的。

plot(Year ~ Average.Life.Expectancy,
     data=subset(dat, Sex == "Both Sexes" & Measure.Variables == "Life Expectancy"),
     col="red", pch=17, 
     main="Male Life Expectancy", ylab="Life Expectancy", xaxt='n', yaxt='n')
axis(1, at=c(48,50,52))
axis(2, at=c(1900, 1902, 1904))

在此处输入图像描述

请注意,我在这里使用了"Both Sexes" ,因为"Male"未包含在您的示例数据中。

另外,我使用 40、50、52 和 1900、1902、1904 来演示轴自定义。

在你的情况下,我会尝试

axis(1, at=3:8*10)
axis(2, at=seq(1900, 2000, 20))

在您的代码中添加一些 arguments 然后使用axis()会很好:

with(subset(LF, Sex == "Male", Measure.Variables == "Life Expectancy"), 
     plot(LF$Year, LF$Average.Life.Expectancy, col="red", pch=17,
          main="Male Life Expectancy", ylab="Life Expectancy"
          ,xlim = c(1900, 2000), ylim = c(30, 80)
          , xaxt='n', yaxt='n'
          )
     )

axis(1, at = seq(1900, 2000, by=20), las = 2)
axis(2, at = seq(30, 80, by=10))

暂无
暂无

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

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