2014-11-03 56 views
2

下面是我用作示例的可重现数据。组类似因素 - 填充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) 

ggplot2绘制我们得到...

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

Graph

这将是有益的,如果我们可以给那些具有相同的类相似颜色的填充。例如,如果蔬菜为蓝色,浆果为粉红色,果实为绿色,您可以看到植物种类的产量,但仍然在视觉上看到名称(这对我们来说更重要)

I觉得我可以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阁楼的一个比例(见@哈德利的意见,例如, here)。因此,在像你这样的情况下,变通是必要的。在ggplot以外产生fill颜色的可能性如下。我使用由包RColorBrewer提供的调色板。您可以轻松检查不同的调色板heredplyr功能用于实际的数据按摩。所产生的颜色随后在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

您可以使用Alpha规模的快速(虽然不完美)的方式来改变的强度一个班级内的颜色:

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))