将颜色插入到ggplot2中指定位置/值的刻度填充渐变中 [英] Insert color into scale fill gradient at specified location / value in ggplot2
问题描述
我已经在ggplot2中创建了一个图,然后在该图的顶部"使用了 geom_rect()
以最低的10%值可视化(红色)数据点 z
.我仍然想使用 scale_fill_gradientn
来填充图例/比例尺,但是我想在填充的最小值处(即垂直比例尺的底部)插入红色.如何使用 scale_fill_gradientn
并执行此操作?或者,如何使用另一种方法来达到预期的效果?
I've created a plot in ggplot2 and then "on top" of that plot I have used geom_rect()
to visualize (in red) the data points with the lowest 10% of values of z
. I would still like to use scale_fill_gradientn
to fill the legend/scale bar, but I would like to insert the color red at the minimum of the fill (i.e. that bottom of the vertical scale). How can I use scale_fill_gradientn
and do this? Or, how can I achieve the desired result using another method?
# The example code here produces an plot for illustrative purposes only.
# create data frame, from ggplot2 documentation
df <- expand.grid(x = 0:5, y = 0:5)
df$z <- runif(nrow(df))
# select min. 10%
df.1 <- df[df$z <= quantile(df$z, 0.1),]
#plot
ggplot(df, aes(x, y, fill = z)) + geom_raster() +
scale_fill_gradientn(colours=topo.colors(7),na.value = "transparent") +
geom_rect(data=df.1, size=1, fill="red", colour=NA , aes(xmin=x-.5, xmax=x+.5, ymin=y-.5, ymax=y+.5))
推荐答案
一种解决方案将提供"red"
作为 scale_fill_gradientn()
中的颜色之一.红色用于两次,以确保范围从0到0.1的所有值都变为红色",然后使用 seq()
将范围从0.1001到1的所有其他值均匀分配.在这种情况下,您不需要第二个数据框.
One solution would be provide "red"
as one of the colors in scale_fill_gradientn()
. Red is used twice to ensure that in range from 0 to 0.1 all values get "red" then with seq()
all other values in range from 0.1001 to 1 are distributed evenly. In this case you don't need a second dataframe.
set.seed(123)
df <- expand.grid(x = 0:5, y = 0:5)
df$z <- runif(nrow(df))
ggplot(df, aes(x, y, fill = z)) + geom_raster() +
scale_fill_gradientn(colours=c("red","red",topo.colors(6)),
values=c(0,0.1,seq(0.1001,1,length.out=7)),na.value = "transparent")
这篇关于将颜色插入到ggplot2中指定位置/值的刻度填充渐变中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!