1

我需要为 ggplot 条形图中的条形分配特定颜色。默认情况下,我得到下面的 ggplot 条形图。在这里,我想要为最高值条分配不同的颜色(比如红色)。那是为 下的64 items酒吧。并且下面的酒吧也是红色的。目前我正在使用下图所示的 R ggplot2 代码。请帮我得到这个。type Dnames X and Z16 itemstype Cname Y

数据:

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

在此处输入图像描述

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

更新

虽然 mnei 提供的代码几乎提供了我需要的东西,但我没有得到图中所示的图例。请让我知道我怎样才能得到它。

4

1 回答 1

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))
于 2012-07-02T00:29:38.823 回答