【问题标题】:How to map ggplot histogram x-axis intervals to fixed colour palette?如何将ggplot直方图x轴间隔映射到固定调色板?
【发布时间】:2023-03-26 01:12:01
【问题描述】:

我正在尝试将我的 ggplot2 直方图分层为固定间隔,并根据特定调色板为它们着色:'x<4':black; '4<x<6':blue; '6<x<8':yellow;等等……

我尝试了两种方法,都没有奏效。

参考我下面的代码,当NoOfElement 下降到一个小数字(例如 500)并且第一个区间 'x<4' 中没有元素时,替代 1 失败。 ggplot2 然后将“黑色”分配给第一个间隔(当 size=500 时,这将是 '4<x<6')。但这不是我想要的(见图)。

在备选方案 2 中,我在数据框中创建了另一个变量,并为每个元素分配了颜色。我这样做是基于对Set specific fill colors in ggplot2 by sign 中给出的解决方案的修改。不幸的是,生成的直方图具有由 ggplot2 随机分配的颜色。

我很困惑,非常感谢一些帮助。提前致谢!

示例代码:

library(ggplot2)

NoOfElement <- 5000; MyBreaks <- c(-Inf, seq(4, 16, by=2), Inf)
MyColours <- c("black", "blue", "yellow", "green", "gray", "brown", "purple", "red")

set.seed(2)
c <- data.frame(a=rnorm(NoOfElement, 10, 2), b=rep(NA, NoOfElement))
c$b <- cut(c$a, MyBreaks)

try <- 1  # Allows toggling of alternatives below
if (try==1)
{
  p <- ggplot( c, aes(x=c$a, fill=c$b) ) + geom_histogram( binwidth=0.2 ) + 
    scale_fill_manual(breaks = levels(c$b), values = MyColours, 
                      name = "X Intervals") + 
    scale_x_continuous( limits=c(2, 20))
}else
{
  c$BarCol <- factor(c$b, levels = levels(c$b), labels = MyColours)

  p <- ggplot( c, aes(x=c$a, fill=c$b) ) + geom_histogram( binwidth=0.2 ) + 
    scale_fill_manual(values = c$BarCol, name = "X Intervals") + 
    scale_x_continuous( limits=c(2, 20))
}
plot (p)

【问题讨论】:

    标签: r colors ggplot2 histogram


    【解决方案1】:

    scale_ 系列中有一个 drop 参数用于空级别:

    NoOfElement <- 500; MyBreaks <- c(-Inf, seq(4, 16, by=2), Inf) 
    MyColours <- c("black", "blue", "yellow", "green", "gray", "brown", "purple", "red")
    
    set.seed(2) 
    c <- data.frame(a=rnorm(NoOfElement, 10, 2), b=rep(NA, NoOfElement)) 
    c$b <- cut(c$a, MyBreaks)
    
    p <- ggplot( c, aes(x=c$a, fill=c$b) ) + geom_histogram( binwidth=0.2 ) + 
        scale_fill_manual(breaks = levels(c$b), values = MyColours, 
                          name = "X Intervals", drop=FALSE)
    

    相关问题here

    【讨论】:

    • 这完美地回答了我的问题。非常感谢您的快速回复!
    猜你喜欢
    • 2012-03-19
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2019-02-27
    • 2019-07-03
    • 1970-01-01
    相关资源
    最近更新 更多