Highlight a single “bar” in ggplot

前端 未结 1 1544
醉话见心
醉话见心 2021-01-18 14:53

i\'d like to choose colors and fill patterns for individual bars in a bar graph (Highlight a single \"bar\")

The bars, that i\'d like to fill in another color are \"

相关标签:
1条回答
  • 2021-01-18 15:31

    scale_fill_manual should work. Create a column in your data that indicates whether the bar should be highlighted or not, then feed that column to the fill aesthetic. scale_fill_manual can then be used to assign colors as desired. Here's a representative example:

    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 )
    

    Note guide = FALSE that hides the legend associated with the ToHighlight column.

    0 讨论(0)
提交回复
热议问题