2012-01-17 16 views
11

Próbuję działki obok siebie następujące zbiory danychwiele histogramy z ggplot2 - pozycja

dataset1=data.frame(obs=runif(20,min=1,max=10)) 
dataset2=data.frame(obs=runif(20,min=1,max=20)) 
dataset3=data.frame(obs=runif(20,min=5,max=10)) 
dataset4=data.frame(obs=runif(20,min=8,max=10)) 

Próbowałem dodać pozycję opcja = „unik” dla geom_histogram bez powodzenia. Jak mogę zmienić poniższy kod, aby wydrukować kolumny histogramów obok siebie bez nakładania się?

ggplot(data = dataset1,aes_string(x = "obs",fill="dataset")) + 
geom_histogram(binwidth = 1,colour="black", fill="blue")+ 
geom_histogram(data=dataset2, aes_string(x="obs"),binwidth = 1,colour="black",fill="green")+ 
geom_histogram(data=dataset3, aes_string(x="obs"),binwidth = 1,colour="black",fill="red")+ 
geom_histogram(data=dataset4, aes_string(x="obs"),binwidth = 1,colour="black",fill="orange") 

Odpowiedz

22

ggplot2 najlepiej z „długich” danych, gdzie wszystkie dane są w jednej ramce danych i inne grupy są opisane w innych zmiennych, w ramce danych. W tym celu

DF <- rbind(data.frame(fill="blue", obs=dataset1$obs), 
      data.frame(fill="green", obs=dataset2$obs), 
      data.frame(fill="red", obs=dataset3$obs), 
      data.frame(fill="orange", obs=dataset3$obs)) 

gdzie dodałem kolumnę fill która ma wartości, które zostały użyte w twoich histogramy. Biorąc pod uwagę, że fabuła może być wykonana z:

ggplot(DF, aes(x=obs, fill=fill)) + 
    geom_histogram(binwidth=1, colour="black", position="dodge") + 
    scale_fill_identity() 

gdzie position="dodge" działa teraz.

enter image description here

Nie trzeba korzystać z dosłownego kolor wypełnienia jako wyróżnienie. Oto wersja, która zamiast tego używa numeru zestawu danych.

DF <- rbind(data.frame(dataset=1, obs=dataset1$obs), 
      data.frame(dataset=2, obs=dataset2$obs), 
      data.frame(dataset=3, obs=dataset3$obs), 
      data.frame(dataset=4, obs=dataset3$obs)) 
DF$dataset <- as.factor(DF$dataset) 
ggplot(DF, aes(x=obs, fill=dataset)) + 
    geom_histogram(binwidth=1, colour="black", position="dodge") + 
    scale_fill_manual(breaks=1:4, values=c("blue","green","red","orange")) 

To jest to samo z wyjątkiem legendy.

enter image description here