这可能是一个非常简单的问题,但我无法理解它。我正在生成How to fill histogram with color gradient?中提出的直方图,并希望使用scale_color_gradient2更改颜色方案。直方图条应根据我的数据集中的连续变量着色,最小值为“darkgreen”,最大值为“red”,中间为“orange”。我还使用scale_color_gradient2的整洁“trans”属性来对图中的数据进行对数转换。不幸的是,应用scale_color_gradient2不起作用,因为我已经在geom_histogram的aes属性中指定了条形的颜色填充。 现在,我很确定ggplot2提供了这样的功能,但我无法弄清楚如何。在应用scale_color_gradient2之前,我是否需要“手动”准备我的数据集,i。即我是否必须使用cut()来产生中断,然后将连续数据分配给那些中断?
示例代码:
myData <- c(1.14697513, 1.17511522, 4.40715049, 12.46033118, 13.31236437,
13.80646742, 14.32024812, 14.27723102, 15.38885253, 18.5314918,
19.54137644, 19.84750311, 19.95955739, 22.16140883, 23.45692625,
26.39371955, 29.84970725, 19.71228586, 23.81598965, 28.8954292,
26.42070425, 24.70807915, 25.25013288, 29.06533739, 19.82372419,
27.8835174, 20.67534068, 21.48039058, 22.90360096, 23.79028599,
23.82270201, 24.75539892, 25.72394072, 24.3639409, 19.84061517,
22.13606982, 24.74780434, 22.37468515, 16.02038647, 15.03168204,
15.49245895, 15.33408853, 15.72013928, 15.92662432, 16.49098242,
31.21540968, 85.36487512, 24.89061536, 22.88268752, 25.45473677,
29.40085037, 24.09764601, 25.90179717, 29.04696969, 29.12589867,
37.06852817, 28.3928621, 27.97867109, 26.11118457, 25.62078501,
25.55879171, 25.47652264, 31.64679767, 28.84595255, 28.06412499,
23.15553981, 26.53143762, 23.88348507, 24.14657713, 25.01563365,
21.65575207, 15.54498242, 16.57195781, 16.79712558, 16.5264702,
15.59375338, 13.81176329, 14.7108595, 18.2395959, 23.32177567,
45.4972562, 63.74298896, 56.24248751, 56.28860198, 48.77159908,
51.359598, 28.59380079, 18.70095675, 15.86502211, 4.99145761,
1.20619987, 1.28706938, 1.39360758, 1.33117437, 1.28165222, 1.20450226,
1.18710708, 1.27730078, 1.55985527, 1.92654237, 1.89138402, 1.29368108,
1.12383576, 1.17094158, 1.17934022)
gg_b <- ggplot_build(ggplot() + geom_histogram(aes(x = myData), binwidth=1))
nu_bins <- dim(gg_b$data[[1]])[1]
ggplot() + geom_histogram(aes(x = myData), binwidth=1,
fill = rainbow(nu_bins, start=4/6)) + scale_color_gradient2(low='darkgreen', mid='orange', high='red', midpoint=2, name= 'mydata', trans = "log2")
# #scale_color_gradient2 obviously does nothing: How do I get it to work?
情节应该看起来像这样:
# #Histogram
hp <- qplot(x =myData, fill=..count.., geom="histogram")
hp
hp + scale_fill_gradient2(low="darkgreen", mid="orange", high="red",
midpoint=2, name= 'mydata', trans = "log2")
但是,条形应根据myData中的连续变量着色,而不是根据计数。
我很确定我错过了一些明显的东西,为此道歉。非常感谢任何帮助!