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

前端之家收集整理的这篇文章主要介绍了正确使用scale_fill_manual()在ggplot2中创建多色直方图条?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一系列我想在R中探索的数据文件,我打算用它来生成一个带有列变量的数据框,我将为此问题标记为foo. foo的范围位于区间[0,7000].作为我的数据探索练习的一部分,我想创建一个foo的一维直方图,但有一点点扭曲:foo在(1000,7000)之间的范围内的值对我来说特别“有趣”,因此我想使用颜色调色板对该数据范围中的单个直方图条进行颜色编码(即,因为稍后我最终打算重复使用相同的调色板来映射我暂时从数据框中省略的其他列中的数据.为了让我的问题变得不必要地变得复杂了.相反,[0,1000]范围内的foo值对我来说并不那么有趣,但是我仍然希望能够在直方图中看到它们,尽管是有色的灰色,存在任何值的情况.

在下面的代码示例中,我生成了一个人工样本数据框,并尝试使用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))

解决方法

您可以将drop参数设置为FALSE.请参阅?discrete_scale:从比例中删除未使用的因子水平(TRUE或FALSE)
ggplot(df,aes(foo)) +
  geom_histogram(aes(fill = colcode),binwidth = bwdth) +
  scale_fill_manual("",breaks = brk,values = colors,drop = FALSE)
原文链接:https://www.f2er.com/css/215793.html

猜你在找的CSS相关文章