2015-09-09 44 views
2

我正嘗試在x軸上生成一個帶有因子的簡單散點圖。得到的圖表顯示水平線條而不是點(不幸的是,不能上傳圖像)。水平軸上的因子散點圖

根據示例3.5從將某些SAS代碼轉錄爲R根據我的教授的要求,Dobson,Bennett的廣義線性模型介紹。目的是向R介紹我的同學,所以我試圖儘可能保持簡單和乾淨。

dat <- data.frame(age_group = c("30-34", "35-39", "40-44", 
    "45-49", "50-54", "55-59", "60-64", "65-69"), 
        deaths = c(1, 5, 5, 12, 25, 38, 54, 65), 
        population = c(17742, 16554, 16059, 13083, 10784, 9645, 10706, 9933)) 
dat <- within(dat, { 
       rate <- deaths/population * 100000 
       lograte <- log(deaths/population * 100000) 
       }) 

我的陰謀

with(dat, plot(age_group, lograte, pch=19)) 

不會產生 '點',我想。我有一個黑客一起解決方案,我會稍後發佈,但想看看是否有更好的方法。再次,道歉,我不能上傳圖像。

回答

3

使用base R可以按照如下方式進行:
將x軸縮小xaxt="n",然後手動添加。

plot(1:nrow(dat), dat$lograte, xaxt="n", xlab="age_group", ylab="lograte", pch=19) 
axis(1, at=1:8, labels=dat$age_group) 

enter image description here

可以使用ggplot2代替基礎R情節實現它:

require(ggplot2) 
ggplot(dat, aes(x=age_group, y=lograte)) + geom_point() 

enter image description here

+0

謝謝你,這是非常有幫助的。如果可能的話,我更喜歡base R,但這是一個很好的解決方案。 – Whitebeard

+0

剛剛更新了答案 – Rentrop

+1

@ Floo0:你比我快。爲了解釋爲什麼山姆的代碼產生了意想不到的結果,我會留下我的答案。 – Stibu

5

plot是R中的通用功能,這意味着,根據它的第一個參數的類,可能會調用不同的函數。由於您的第一個參數是一個因素,因此調用的函數是plot.factor。從plot.factor文檔:

對於數字爲y的箱線圖使用

所以,箱線圖就是你得到的。如果你想避免這種情況,你可以轉換到age_group數字:

with(dat, plot(as.numeric(age_group), lograte, pch=19)) 

這可能不會產生你想要的軸,因爲標籤簡單地從1運行8.您可以產生無x軸的情節然後用第二個命令添加軸:

with(dat, plot(as.numeric(age_group), lograte, pch=19, xaxt = "n", xlab = "age group")) 
axis(1, 1:8, dat$age_group) 

我還添加了軸標籤。這給出了以下情節:

enter image description here

+0

感謝有關'plot.factor'的情節和解釋。這非常有幫助。 – Whitebeard