2013-05-13 122 views
20

我試圖用下面的代碼爲每個配置文件生成一個圖表,但我不斷收到「至少有一個圖層必須包含用於構建切面的所有變量」。錯誤。我花了幾個小時試圖讓它工作,但我不能。如何在ggplot2中正確使用facet_grid?

我相信anwser一定很簡單,任何人都可以幫忙嗎?

d = structure(list(category = structure(c(2L, 2L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 
3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("4X4", 
"HATCH", "SEDAN"), class = "factor"), profile = structure(c(1L, 
1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 
1L), .Label = c("FIXED", "FREE", "MOBILE"), class = "factor"), 
    value = c(6440.32, 6287.22, 9324, 7532, 7287.63, 6827.27, 
    6880.48, 7795.15, 7042.51, 2708.41, 1373.69, 6742.87, 7692.65, 
    7692.65, 8116.56, 7692.65, 7692.65, 7692.65, 7962.65, 8116.56, 
    5691.12, 2434, 8343, 7727.73, 7692.65, 7721.15, 1944.38, 
    6044.23, 8633.65, 7692.65, 7692.65, 8151.65, 7692.65, 7692.65, 
    2708.41, 3271.45, 3333.82, 1257.48, 6223.13, 7692.65, 6955.46, 
    7115.46, 7115.46, 7115.46, 7115.46, 6955.46, 7615.46, 2621.21, 
    2621.21, 445.61)), .Names = c("category", "profile", "value" 
), class = "data.frame", row.names = c(NA, -50L)) 

library(ggplot2) 

p = ggplot(d, aes(x=d$value, fill=d$category)) + geom_density(alpha=.3) 
p + facet_grid(d$profile ~ .) 

回答

34

你的問題來自參照變量明確(即d$profile),而不是相對於在調用ggplotdata說法。任何地方都不需要d$

faceting使用facet_gridfacet_wrap時,您需要這樣做。這也是很好的做法在電話做aes

p = ggplot(d, aes(x=value, fill=category)) + geom_density(alpha=.3) 
p + facet_grid(profile ~ .) 

enter image description here

相關問題