为ggplots中的特定条指定不同的颜色

时间:2012-07-01 23:51:05

标签: r ggplot2

我需要在ggplot条形图中为条形指定特定颜色。默认情况下,我得到下面的ggplot条形图。在这里,我想要的是为最高值条指定不同的颜色(比如说红色)。这适用于64 itemstype D names X and Z 16 items下的条形图。 type C下的条形图为红色,name Ydata <- structure(list(type = structure(c(1L, 2L, 3L, 4L, 2L, 3L, 4L, 3L, 4L, 4L, 1L, 2L, 3L, 4L, 2L, 3L, 4L, 3L, 4L, 4L, 1L, 2L, 3L, 4L, 2L, 3L, 4L, 3L, 4L, 4L), .Label = c("A", "B", "C", "D"), class = "factor"), items = c(16L, 16L, 16L, 16L, 32L, 32L, 32L, 48L, 48L, 64L, 16L, 16L, 16L, 16L, 32L, 32L, 32L, 48L, 48L, 64L, 16L, 16L, 16L, 16L, 32L, 32L, 32L, 48L, 48L, 64L), name = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("X", "Y", "Z"), class = "factor"), value = c(6.3, 7.2, 7.1, 7, 10, 10.9, 11, 11.6, 11.5, 12, 8.9, 10.6, 11.5, 7.9, 12.6, 13.5, 12.4, 13, 14, 15.4, 4.8, 7, 7.2, 6.1, 4.1, 4.4, 4.2, 3.2, 2.7, 1.6)), .Names = c("type", "items", "name", "value" ), class = "data.frame", row.names = c(NA, -30L)) 条形图。目前我正在使用下图所示的R ggplot2代码。请帮我搞定。

数据:

data$name = factor(data$name, levels(data$name)[c(1,3,2)])
p1 = ggplot(data, aes(type, value, fill=type, group=items, facets=items)) + geom_bar(stat="identity") 
p1 = p1 +  scale_fill_manual(values = rep("grey60",4), labels = c("type-A", "type-B", "type-C", "type-D"))
p1 = p1 + facet_grid(name~items,scales="free", space="free") + opts(strip.text.y = theme_text(size=14, face="bold"))
p1 = p1 + opts(legend.position="top", legend.text=theme_text(size=15), legend.title=theme_text(size=0,colour="white"), legend.key = theme_rect(colour = NA))

enter image description here

{{1}}

更新

尽管mnei提供的代码几乎提供了我需要的代码,但我没有得到图中所示的图例。请让我知道如何获得。

1 个答案:

答案 0 :(得分:3)

计算每个组合的最大type

 library(plyr)
 data <- ddply(data, .( items, name), mutate, is_max = type == type[which.max(value)])

## the plot
ggplot(data, aes(x = type, y = value, fill = is_max, group = items)) + 
  facet_grid(name ~ items, scale = 'free', space = 'free') + 
  geom_bar(stat = 'identity') +  
  scale_fill_manual(values = c('black', 'red'), labels = c('other', 'maximum')) +
  opts(legend.position = "top", legend.text = theme_text(size = 15),  
       legend.title = theme_text(size = 0,colour = "white"), 
       legend.key = theme_rect(colour = NA))

或者根据要求提供图例

 ggplot(data, aes(x=type, y= value, group = items, fill = type)) +  
  facet_grid(name~items, scale = 'free', space = 'free') + 
  geom_bar(stat= 'identity')  +
  geom_bar(data = data[data$is_max,],stat = 'identity', fill = 'red' ) +
  scale_fill_manual(values = rep("grey60",4), 
                    labels = c("type-A", "type-B", "type-C", "type-D")) + 
  opts(strip.text.y = theme_text(size=14, face="bold")) + 
  opts(legend.position="top", legend.text=theme_text(size=15), 
       legend.title=theme_text(size=0,colour="white"), 
       legend.key = theme_rect(colour = NA))