正确使用scale_fill_manual()在ggplot2中创建多色直方图条?

sta*_*yra 8 r ggplot2

我有一系列我想在R中探索的数据文件,为了这个问题的目的,我计划用它来生成一个带有我将标记的列变量的数据框foo.foo沿着区间[0,7000] 的谎言范围.作为我的数据探索练习的一部分,我想创建一个1D直方图foo,但有点扭曲:foo在(1000,7000)之间的范围内的值对我来说特别"有趣",因此我我希望使用颜色调色板对该数据范围内的单个直方图条进行颜色编码(即,因为稍后我最终打算重复使用相同的调色板来映射我暂时从数据框中省略的其他列的数据让我的问题变得不必要地变得复杂了.相反,foo[0,1000]范围内的值对我来说并不那么有趣,但是我仍然希望能够在直方图中看到它们,尽管是灰色的,在存在任何值的情况下.

在下面的代码示例中,我生成了一个人工样本数据框,并尝试使用ggplot2选择填充颜色来绘制直方图scale_fill_manual().我确实得到了一个多色的直方图,但它看起来并不像预期的那样:ggplot2似乎忽略了我在颜色之间放置断点的指示.具体来说,问题似乎与丢失的数据有关:碰巧没有数据的间隔似乎没有映射到颜色,尽管我的意图是它们应该是.这也意味着灰色最终会被映射到区间(1000,1500),而不是像我预期的那样被映射到[0,1000].

我的问题:如何强制ggplot2将特定颜色填充代码分配给特定数据范围,即使某些间隔为空并且没有数据,因此不会生成与这些间隔对应的直方图条?

我在下面包含了我的代码的初始版本,以及一个虚拟示例数据框以及它生成的输出的手工注释版本.

library(ggplot2)

# Minimum and maximum values of interest (for other data sets, additional
# values that are of lesser interest may fall within the interval [0, 1000])
lolim<-1000
hilim<-7000
bwdth<-500
# Construct sample data frame
df<-data.frame(foo=c(1200, 1300, 1750, 2200, 2300, 2750, 3200, 3300, 3750,
                     4200, 4300, 4750, 6200, 6300, 6750))
# Construct a discrete factor variable which can later be mapped onto
# discrete color codes
df$colcode<-cut(df$foo, breaks=c(0, seq(lolim, hilim, bwdth)),
                include.lowest=TRUE)

# Create the breaks and color codes to be used by scale_fill_manual()
brk<-levels(df$colcode)
ncol<-length(brk)
# My expectation is that "#808080FF" (gray) will map onto the range
# [0, 1000], while a palette consisting of 12 sequential shades of the
# rainbow will be mapped onto the range (1000, 7000], in intervals of 500
colors<-c("#808080FF", rainbow(ncol-1))

# Draw the histogram
print(ggplot(df, aes(foo)) +
        geom_histogram(aes(fill=colcode), binwidth=bwdth) +
        scale_fill_manual("", breaks=brk, values=colors))
Run Code Online (Sandbox Code Playgroud)

手工注释的样本输出

Hen*_*rik 9

您可以将drop参数设置为FALSE.见?discrete_scale:drop unused factor levels from the scale (TRUE or FALSE)

ggplot(df, aes(foo)) +
  geom_histogram(aes(fill = colcode), binwidth = bwdth) +
  scale_fill_manual("", breaks = brk, values = colors, drop = FALSE)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述