突出显示单个" bar"在ggplot中

时间:2017-08-22 14:21:10

标签: r ggplot2 bar-chart

我希望在条形图中为单个条形图选择颜色和填充图案(突出显示单个"条形图")

我想填写另一种颜色的酒吧是" Str"和" RB" enter image description here

ggplot(GZ.mean, aes(x=Group.1, y=B)) +theme_bw(base_size=20, base_family="Times")+
geom_bar(stat="identity",colour="black", width=.6, position = "dodge", ,fill="gainsboro") +geom_errorbar(my.limits, width=0.2) +
theme(axis.text.x=element_text(family="Times", colour="black", size=rel(1.2), angle=30, hjust=1, vjust=1))+
theme(axis.text.y=element_text(family="Times", colour="black", size=rel(1.2))) +   scale_y_continuous(limits=c(0,170))+geom_text(size=6,aes(label=c("a","d","c","e","b","d","d","b","bc","d", "bc"),hjust=offset.h, vjust=offset.v)) +
scale_x_discrete(limits=c("JdC", "Stu", "Str", "Bol", "WBr", "Rij4", "Bif", "ErL", "ZtG", "PdV", "RB")) +labs(x= "Variety", y= "Total Sugar concentration [mg * g-1 FW]")

我已经尝试过" scale_fill_manual"和" scale_color_manual"但它仍然无法运作。

1 个答案:

答案 0 :(得分:7)

scale_fill_manual应该有效。在数据中创建一个列,指示是否应突出显示该栏,然后将该列提供给fill美学。然后可以使用scale_fill_manual根据需要指定颜色。这是一个有代表性的例子:

library( tidyverse )
library( ggplot2 )

## Generate some data to plot
X <- mtcars %>% group_by( cyl ) %>% summarize( mpg = mean(mpg) ) %>% ungroup

## Add a column indicating whether the category should be highlighted
X <- X %>% mutate( ToHighlight = ifelse( cyl == 6, "yes", "no" ) )

## Data looks like this
## A tibble: 3 x 3
##    cyl      mpg ToHighlight
##  <dbl>    <dbl>       <chr>
##1     4 26.66364          no
##2     6 19.74286         yes
##3     8 15.10000          no

## Plot the data
ggplot( X, aes( x = cyl, y = mpg, fill = ToHighlight ) ) +
    geom_bar( stat = "identity" ) +
    scale_fill_manual( values = c( "yes"="tomato", "no"="gray" ), guide = FALSE )

注意隐藏与guide = FALSE列关联的图例的ToHighlight

enter image description here