2014-11-03 6 views
2

다음은 재현 가능한 데이터를 예로 들어 설명합니다. ggplot2 플롯 할 때유사한 요소 그룹화 - 채우기 ggplot2

Name <- c("Blueberry", "Raspberry", "Celery", "Apples", "Peppers") 
Class <- c("Berries", "Berries", "Vegetable", "Fruit", "Vegetable") 
Yield <- c(30, 20, 15, 25, 40) 
example <- data.frame(Class = Class, Name = Name, Yield = Yield) 

우리는 ... 얻을

ggplot(example, aes(x = Name, y = Yield, fill = Name))+ 
    geom_bar(stat = "identity") 

Graph

우리는 같은 클래스가 그와 유사한 색상의 칠을 줄 수 있다면 그것은 도움이 될 것

. 예를 들어 채소가 푸른 색을 띠면 열매는 분홍색이었고 열매는 녹색이었으며 식물의 등급에 따라 수확량을 볼 수 있었지만 여전히 그 이름을 시각적으로 볼 수 있습니다 (우리에게 더 중요합니다)

내가 scale_fill_hue()으로이 작업을 수행 할 수 있다고 생각하지만 난 그게

ggplot(example, aes(x = Name, y = Yield))+ 
    geom_bar(aes(fill = Class),stat = "identity")+ 
    scale_fill_hue("Name") 

Class

답변

2

ggplot의 기본 설계는 aes (@ hadley의 의견을 참조하십시오. here). 따라서 귀하의 경우와 같은 경우에는 해결 방법이 필요합니다. 다음은 ggplot 외부에서 fill 색상이 생성되는 한 가지 경우입니다. 나는 패키지 RColorBrewer에서 제공하는 색상 표를 사용합니다. 다른 팔레트 here을 쉽게 확인할 수 있습니다. dplyr 함수는 실제 데이터 마사지에 사용됩니다. 생성 된 색상은 scale_fill_manual에 사용됩니다

library(dplyr) 
library(RColorBrewer) 

# create look-up table with a palette name for each Class 
pal_df <- data.frame(Class = c("Berries", "Fruit", "Vegetable"), 
        pal = c("RdPu", "Greens", "Blues")) 

# generate one colour palette for each Class 
df <- example %>% 
    group_by(Class) %>% 
    summarise(n = n_distinct(Name)) %>% 
    left_join(y = pal_df, by = "Class") %>% 
    rowwise() %>% 
    do(data.frame(., cols = colorRampPalette(brewer.pal(n = 3, name = .$pal))(.$n))) 

# add colours to original data 
df2 <- example %>% 
    arrange(as.integer(as.factor(Class))) %>% 
    cbind(select(df, cols)) %>% 
    mutate(Name = factor(Name, levels = Name)) 

# use colours in scale_fill_manual 
ggplot(data = df2, aes(x = Name, y = Yield, fill = Name))+ 
    geom_bar(stat = "identity") + 
    scale_fill_manual(values = df2$cols) 

enter image description here

가능한 확장은 각각의 '클래스 규모'에 대해 별도의 전설을 작성하는 것입니다. 예 : 내 이전 시도 here (second example)here.

0

당신은의 강도를 변경하는 방법 (완벽하지 불구하고) 빠른로 알파 스케일을 사용할 수있는 작업을 얻이 수없는 것 수업 내 컬러 :

library("ggplot2"); theme_set(theme_bw()) 
library("plyr") 
## reorder 
example <- mutate(example, 
       Name=factor(Name,levels=Name)) 
example <- ddply(example,"Class",transform,n=seq_along(Name)) 
g0 <- ggplot(example, aes(x = Name, y = Yield)) 
g0 + geom_bar(aes(fill = Class,alpha=factor(n)),stat = "identity")+ 
    scale_alpha_discrete(guide=FALSE,range=c(0.5,1))