Histogram conditional fill color

后端 未结 2 1703
情歌与酒
情歌与酒 2020-12-06 11:59

I would like to make a histogram where the fill color changes depending on the low end of the bin. I do not want a manual fill. This answer seems promising, but I could no

相关标签:
2条回答
  • 2020-12-06 12:28

    It would be easiest to just add another column with the condition and update the aes to include the fill group.

    cust$high_rev <- as.factor((cust[,2]>100000)*1)
    
    ggplot(cust, aes(cust_rev, fill=high_rev)) + 
        geom_histogram(color="black", binwidth=1/3) + 
        scale_x_log10(labels=comma, breaks=powers(10,8)) +
        scale_y_continuous(labels=comma) +
        xlab("Customer Revenue") + ylab("Number of Customers") +
        ggtitle("Distribution of Customer Value")
    

    enter image description here

    If you have your heart set on some specific colors you can use the scale_fill_manual function. Here is an example with some fun bright colors.

    ggplot(cust, aes(cust_rev, fill=high_rev)) + 
        geom_histogram(color="black", binwidth=1/3) + 
        scale_x_log10(labels=comma, breaks=powers(10,8)) +
        scale_y_continuous(labels=comma) +
        scale_fill_manual(values = c("green", "purple")) +
        xlab("Customer Revenue") + ylab("Number of Customers") +
        ggtitle("Distribution of Customer Value")
    

    enter image description here

    0 讨论(0)
  • 2020-12-06 12:32

    How about this one?

    ggplot(cust, aes(cust_rev)) + 
      geom_histogram(aes(fill=cust_rev > 100000),binwidth=1/3) + 
      scale_x_log10()
    

    or equivalently

    ggplot(cust, aes(x=cust_rev,fill=cust_rev > 100000)) + 
      geom_histogram(binwidth=1/3) + 
      scale_x_log10()
    
    0 讨论(0)
提交回复
热议问题