我正在尝试根据以下代码使用scale_color_gradientn (ggplot2 package)
绘制从1到6的一些数据范围。默认情况下,guide_color_bar
会将标签放在图例中垃圾箱的“中心”(请参见代码块1)。但是我想将标签设置为每个垃圾箱的“上”和“下”边界。我尝试相应地设置中断和标签,但是2,3,4,5正确对齐,但是1,6没有显示(请参见代码block2)。
请参阅随附的代码。
library(ggplot2)
###provide dataset
dat <- data.frame(list(x = c(0.214137620411313,0.553775825041679,-1.0595195186151,
-1.61004932625145,-0.338151062634607,0.204937753426245,
-0.224345039271189,-0.909609704018834,-0.808109884248038,
0.553083514142192,-0.389177932603183,-0.447245638594407,
-0.0211388451690059,-0.599417455124725,-0.310866189554078,
-0.681632468885545,-0.202055723512808,1.11680032924059,0.82599921267075,1.2509189798129),
y = c(2.60809809498069,-0.051039961195504,2.22719419433773,-0.0138721238155097,-1.54739969676097,
-1.37988910915699,1.47987074083825,-0.254921944338877,-0.326280380145921,-0.726638665692272,
-1.95234864995199,0.422940041768889,1.18168478575317,0.91795937727616,0.0954675468852296,
-1.68443178674375,0.990329350606127,-0.707831781928625,-0.594029169314093,-1.06589703339072)),
z = c(1,3,3,1,2,2,2,4,2,1,1,1,1,5,2,4,3,4,1,4))
###define breaks and colors
my_breaks <- c(0,1,2,3,4,5,6)
colors <- c('#e41a1c','#377eb8','#4daf4a',
'#ff7f00','#ffff33','#a65628')
###the label is in the center.
ggplot(dat, aes(x,y,color=z, label = round(z,2))) + geom_point() +
scale_color_gradientn(
colours = colors,
values = scales::rescale(c(1:6)),
limit = c(1,6),
guide = guide_colourbar(nbin = 6, raster = FALSE, frame.colour = "black", ticks.colour = NA,
direction = "horizontal",
barwidth = 30, barheight = 2, label.hjust = 0)) +
geom_text() +
theme(legend.position = 'bottom')
###the label shows the upper and lower boundary for each bin, but the beginning (1) and ending (6) is not showing.
ggplot(dat, aes(x,y,color=z, label = round(z,2))) + geom_point() +
scale_color_gradientn(
colours = colors,
values = scales::rescale(c(1:6)),
limit = c(1,6),
breaks = c(1:7)-0.5, ###the label should be at 0.5,1.5,2.5,...,6.5
labels = my_breaks,
guide = guide_colourbar(nbin = 6, raster = FALSE, frame.colour = "black", ticks.colour = NA,
direction = "horizontal",
barwidth = 30, barheight = 2, label.hjust = 0)) +
geom_text() +
theme(legend.position = 'bottom')
感谢您的帮助。
答案 0 :(得分:0)
可能不是最优雅的,但请看以下内容。我还对您的点标签进行了一些调整。
fn scanl<T, F>(op: F, initial: T, list: &[T]) -> Vec<T>
where
F: Fn(&T, &T) -> T,
{
let mut acc = Vec::with_capacity(list.len());
acc.push(initial);
list.iter().fold(acc, |mut acc, val| {
acc.push(op(val, acc.last().unwrap()));
acc
})
}
//scanl(|x, y| x + y, 0, &[1, 2, 3, 4, 5])
由reprex package(v0.3.0)于2019-06-14创建