组相似的因素 - 填充ggplot2

时间:2014-11-03 23:03:28

标签: r 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

如果我们能够为具有相同类别的颜色填充相似颜色,那将会很有帮助。例如,如果蔬菜是深蓝色,浆果是粉红色,水果是绿色的阴影,你可以看到植物类的产量,但仍然在视觉上看到名称(这对我们来说更重要)

我觉得我可以用scale_fill_hue()完成这项任务,但我似乎无法让它工作

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

Class

2 个答案:

答案 0 :(得分:2)

ggplot中的基本设计是每个aes主题的一个比例(请参阅@ hadley的意见,例如here)。因此,在像您这样的情况下,需要解决方法。这是在fill之外生成ggplot颜色的一种可能性。我使用包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

答案 1 :(得分: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))