nof*_*lly 18 label r legend fill ggplot2
我在创建打印ggplot2使用scale_fill_gradientn.我想在缩放图例的最小值和最大值处添加文本.例如,在图例最小显示"最小"和图例最大显示"最大".有些帖子使用离散填充并添加带有数字而不是文本的标签(例如此处),但我不确定如何使用该labels功能scale_fill_gradientn仅在最小和最大时插入文本.目前我很容易出错:
Error in scale_labels.continuous(scale, breaks) :
Breaks and labels are different lengths
Run Code Online (Sandbox Code Playgroud)
这种类型的缩放/填充是否可以在ggplot2中使用此文本标签?
# 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))
#plot
ggplot(df, aes(x, y, fill = z)) + geom_raster() +
scale_fill_gradientn(colours=topo.colors(7),na.value = "transparent")
Run Code Online (Sandbox Code Playgroud)
Did*_*rts 36
因为scale_fill_gradientn()你应该提供两个参数:breaks=并且labels=具有相同的长度.通过参数,limits=您可以将颜色条扩展为所需的最小值和最大值.
ggplot(df, aes(x, y, fill = z)) + geom_raster() +
scale_fill_gradientn(colours=topo.colors(7),na.value = "transparent",
breaks=c(0,0.5,1),labels=c("Minimum",0.5,"Maximum"),
limits=c(0,1))
Run Code Online (Sandbox Code Playgroud)

在我看来,用户 Didzis Elfert 的回答稍微缺乏“自动性”(但它当然指出了问题的核心+1:)。这里有一个选项可以以编程方式定义数据的最小值和最大值。
优点:
library(ggplot2)
foo <- expand.grid(x = 0:5, y = 0:5)
foo$z <- runif(nrow(foo))
myfuns <- list(Minimum = min, Mean = mean, Maximum = max)
ls_val <- unlist(lapply(myfuns, function(f) f(foo$z)))
# you only need to set the breaks argument!
ggplot(foo, aes(x, y, fill = z)) +
geom_raster() +
scale_fill_gradientn(
colours = topo.colors(7),
breaks = ls_val
)
Run Code Online (Sandbox Code Playgroud)

# You can obviously also replace the middle value with sth else
ls_val[2] <- 0.5
names(ls_val)[2] <- 0.5
ggplot(foo, aes(x, y, fill = z)) +
geom_raster() +
scale_fill_gradientn(
colours = topo.colors(7),
breaks = ls_val
)
Run Code Online (Sandbox Code Playgroud)
