Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use facet_grid correctly in ggplot2?

Tags:

r

ggplot2

I'm trying to generate one chart per profile with the following code, but I keep getting "At least one layer must contain all variables used for facetting." errors. I spent the last few hours trying to make it work but I couldn't.

I believe the anwser must be simple, can anyone help?

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 ~ .)
like image 513
Guilherme Coutinho Avatar asked May 13 '13 04:05

Guilherme Coutinho


People also ask

What is the function of Facet_grid () in Ggplot ()?

facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.

What is the difference between Facet_wrap and Facet_grid?

While facet_grid shows the labels at the margins of the facet plot, facet_wrap creates a label for each plot panel.

What is faceting in Ggplot?

Faceting is the process that split the chart window in several small parts (a grid), and display a similar chart in each section. Each section usually shows the same graph for a specific group of the dataset. The result is usually called small multiple.


1 Answers

Your problem comes from referring to variables explicitly (i.e. d$profile), not with respect to the data argument in the call to ggplot. There is no need for d$ anywhere.

When faceting using facet_grid or facet_wrap, you need to do so. It is also good practice to do in calls to aes

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

enter image description here

like image 90
mnel Avatar answered Oct 22 '22 06:10

mnel