2015-09-20 29 views
3

我正在研究波士頓數據集,並試圖查看每個圖表上8個房間數據的位置。我已經評論了給我錯誤的那條線。如何將vline添加到facet_grid中的所有圖形?

我必須在對應於rm = 8的所有點處添加垂直線,以查看網格的每個圖形中的數據傳播。我想知道: 1.我做錯了什麼。 2.一種更好的方式找到/代表的數據點,其中RM = 8

library(ggplot2) 
library(reshape2) 
library(MASS) 
library(data.table) 

data("Boston") 
Boston <- as.data.table(Boston) 

molten_boston <- Boston[, `:=`(rm = round(rm), 
            nox = nox * 100, 
            chas = chas * 10)] 
molten_boston <- melt(data = molten_boston, id.vars = "rm") 

comments_bar <- ggplot(molten_boston) + 
    geom_bar(binwidth = 1, aes(x = value), color = "black", fill = "salmon") + 
    # geom_vline(data = molten_boston[rm == 8, .SD, by = variable, .SDcols = "value"], aes(xintercept = value)) + 
    facet_wrap(~ variable, scales = "free") 
print(comments_bar) 
+2

此代碼似乎產生預期的結果。你遇到了什麼錯誤? – jlhoward

回答

0

我沒有包data.table,因此如果問題出在data.table一部分,我不能告訴的代碼或不。但你需要每個房間的大小單個值,所以

Boston$rm = round(Boston$rm) 
molten_boston <- melt(data =Boston, id.vars = "rm") 
rm.means = aggregate.data.frame(molten_boston$value,by=molten_boston[,1:2],FUN=mean) 
comments_bar <- ggplot(molten_boston) + 
    geom_bar(binwidth = 1, aes(x = value), color = "black", fill = "salmon") + 
    geom_vline(data = rm.means[rm.means$rm==8,], aes(xintercept = x)) + 
    facet_wrap(~ variable, scales = "free") 
print(comments_bar) 

似乎工作。

+2

我想他想在每個方面畫很多垂直線條。代碼已經在做。 – Axeman

1

另外一個可視化將堆疊條形,它看起來OK大當:

molten_boston$EightRooms <- as.factor(molten_boston$rm == 8) 
molten_boston$EightRooms <- relevel(molten_boston$EightRooms, 2) 

ggplot(molten_boston, aes(x = value, fill = EightRooms)) + 
    geom_bar(binwidth = 1, color = "black") + 
    facet_wrap(~ variable, scales = "free") 

enter image description here

使用背景中的密度圖將是很好的,但在這種情況下,因爲有點棘手的y軸的變化。你可能需要做一些預先計算。這是我最好的嘗試:

ggplot(molten_boston, aes(x = value)) + 
    geom_density(data = subset(molten_boston, rm == 8), aes(y =..density.. * 300), 
       fill = 'blue', alpha = 0.5) + 
    geom_bar(binwidth = 1, color = "black", fill = "salmon", alpha = 0.5) + 
    facet_wrap(~ variable, scales = "free") 

enter image description here

1

另一種方式做,這將使用地毯,情節,在頂部的地毯。這與使用geom_vline(...)或多或少相同,但是線條不會一直向下延伸,使條紋變得模糊不清。另外,我不明白你爲什麼要使用binwidth=1

ggplot(molten_boston) + 
    geom_bar(aes(x = value), color = "grey50", fill = "salmon") + 
    geom_rug(data=molten_boston[rm==8,value, by=variable], 
      aes(x=value), sides="t", color="blue") + 
    facet_wrap(~ variable, scales = "free") 

相關問題