簡體   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