change color of only one bar in ggplot

后端 未结 2 902
梦毁少年i
梦毁少年i 2020-12-14 19:00

I want to color only one bar in ggplot. This is my data frame:

area <- c(\"Północ\", \"Południe\", \"Wschód\", \"Zachód\")
sale <- c(16.5, 13.5, 14, 13         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 19:23

    Option 1: Change color of only one bar. Following Henrick's suggestion, you can create a new variable with NAs for the default color and character strings/factors for non-default colors (the first one happens to be red):

    area.color <- c(NA, "withcolor", NA, NA)
    plot.sale.bad <- ggplot(data=df.sale, aes(x=area, y=sale, fill=area.color)) +
      geom_bar(stat="identity") +
      xlab(colnames(df.sale)[1]) +
      ylab(colnames(df.sale)[2]) +
      ggtitle("Porównanie sprzedaży") 
    plot.sale.bad
    

    Option 2: Find the name of the default dark gray color you like. This is not the default color if you simply remove the scale_fill_manual line in your original code (in that case, you get four different pastels), so I assume you mean the grey color produced by the code chunk just above this paragraph, for those bars where area.color==NA. In that case, you might look at the source code (or args, anyway) for scale_fill_discrete:

    > args(scale_fill_discrete)
    # function (..., h = c(0, 360) + 15, c = 100, l = 65, h.start = 0, 
    #     direction = 1, na.value = "grey50") 
    # NULL
    

    The default for na.value is "grey50". So if you wanted to use scale_fill_manual, you could do it like so:

    plot.sale.bad <- ggplot(data=df.sale, aes(x=area, y=sale, fill=area)) +
      geom_bar(stat="identity") +
      scale_fill_manual(values=c("grey50", "red", "grey50", "grey50")) +
      xlab(colnames(df.sale)[1]) +
      ylab(colnames(df.sale)[2]) +
      ggtitle("Porównanie sprzedaży") 
    plot.sale.bad
    

提交回复
热议问题