R ggplot2:在分块图中以离散 类 对连续数据进行分类

R ggplot2: Classify continuous data in discrete classes in tiled graph

我有一个填充的 ggplot 等高线图,描绘了 100x100 网格上的连续 R 平方值。默认情况下,图例以类似连续方式的渐变方式描述值,这是由数据的连续性质产生的。

但是,我想 class 化和可视化 classes 中的数据,每个覆盖 0.05 R 平方值的范围(即 class 1 = 0.00 -0.05,class 2 = 0.05-0.10 等)。我尝试了几个命令,例如 scale_fill_brewer 和 scale_fill_gradient2。后者实际上会生成某种离散的 classes,但 class 标签描述了中断值而不是 class 范围。 Scale_fill_brewer returns 连续数据被强制到离散尺度的错误,这是有道理的,虽然我看不出如何解决它。

为了让事情变得更复杂,我更喜欢使用多样化的调色板,以便更容易识别特定的 classes。此外,我有许多具有不同最大 R 平方值的不同等高线图。所以理想情况下,代码是通用的,也可以很容易地用于其他情节。

到目前为止,这是我的代码:

library(scales)
library(ggplot2)
p1 <- ggplot(res, aes(x=Var1, y=Var2, fill=R2)) +
  geom_tile
p1 +
 theme(axis.text.x=element_text(angle=+90)) +
 geom_vline(xintercept=c(seq(from = 1, to = 101, by = 5)),color="#8C8C8C") +
 geom_hline(yintercept=c(seq(from = 1, to = 101, by = 5)),color="#8C8C8C") +
 labs(list(title = "Contour plot of R^2 values for all possible correlations between Simple Ratio indices & Nitrogen Content", x = "Wavelength 1 (nm)", y = "Wavelength 2 (nm)")) +
 scale_x_discrete(breaks = c("b450","b475","b500","b525","b550","b575","b600","b625","b650","b675","b700","b725","b750","b775","b800","b825","b850","b875","b900","b925","b950")) +
 scale_y_discrete(breaks = c("b450","b475","b500","b525","b550","b575","b600","b625","b650","b675","b700","b725","b750","b775","b800","b825","b850","b875","b900","b925","b950")) +
 scale_fill_continuous(breaks = c(seq(from = 0, to = 0.7, by = 0.05)), low = "black", high = "green")

此时的输出如下所示:

您可能会使用什么scale_fill_gradientn() 未经测试,因为您未能提供可重现的示例

library(scales)
library(ggplot2)
ggplot(res, aes(x=Var1, y=Var2, fill=R2)) +
  geom_tile() + 
  scale_fill_gradientn(
      colours = terrain.colors(15), 
      breaks = seq(from = 0, to = 0.7, by = 0.05)
  )