突出显示ggplot中具有特定值的特定条形图

时间:2017-09-04 23:14:24

标签: r ggplot2 histogram

我目前正在处理数据集" diamond",它包含在R.中。具体来说,我试图突出显示605的钻石价格,最常发生(132次)

我的代码如下:

library(ggplot2)

ggplot(diamonds) +
geom_histogram(aes(x=price), 
             binwidth = 10, 
             breaks = seq(250, 1000, 10),
             color = "black") + 
scale_fill_manual(values = c("[250,590]" = "#FF0000", "[600,610]" = "#FF9999", "[620,1000]" = "#FF0000"))

除了填写特定的间隔之外,我似乎把一切都弄好了。

我真的很感激帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用cut

#Use cut to divide price into groups and table to count frequency of each group
temp = data.frame(table(cut(x = diamonds$price, breaks = seq(250, 1000, 10))))
ggplot(diamonds) +
    geom_histogram(
        aes(x = price),
        binwidth = 10,
        breaks = seq(250, 1000, 10),
        color = "black",
        #For the group with maximum value, assign red, otherwise assign black
        fill = replace(rep("black", NROW(temp)), which.max(temp$Freq), "red"))

enter image description here