簡體   English   中英

R ggplot 如何選擇具有 2 個值的柵格的 colors

[英]R ggplot How do I choose the colors of a raster with 2 values

這是我的問題的一個簡單示例。 步驟是 1. 創建一個具有 10 行、10 列且所有像元值為 0 或 1 的 SpatRaster(terra 的柵格版本)。步驟 2. 轉換為數據框並重命名列。 步驟 3. 使用 ggplot 創建一個圖表。 它為colors使用藍色和黑色,並有一個連續的圖例。

library(terra)
x <- rast(nrow=10, ncol=10, xmin=0, xmax=1)
values(x) <- sample(c(0,1), replace=TRUE, size=100)
x_df <- as.data.frame(x, xy = TRUE)
names(x_df) <- c("x", "y", "value")
col1 <- c("red", "green")
g <- ggplot(data = x_df, aes(x, y,  fill = value)) +
  geom_tile()

現在我想將 colors 更改為 col1 中的那些。 我嘗試將colors = col1放在 ggplot aes 部分及其外部、geom_tile 中的 aes 以及其他一些選項中。 幾乎所有都返回錯誤消息Error: Aesthetics must be either length 1 or the same as the data (100): xxx

value轉換為因子解決了一個問題(圖例現在是離散的 0,1),但我仍然無法弄清楚在哪里添加代碼來更改默認的兩個 colors。

這是我的問題的一個簡單示例。 步驟是 1. 創建一個具有 10 行、10 列且所有像元值為 0 或 1 的 SpatRaster(terra 的柵格版本)。步驟 2. 轉換為數據框並重命名列。 步驟 3. 使用 ggplot 創建一個圖表。 它為colors使用藍色和黑色,並有一個連續的圖例。

library(terra)
x <- rast(nrow=10, ncol=10, xmin=0, xmax=1)
values(x) <- sample(c(0,1), replace=TRUE, size=100)
x_df <- as.data.frame(x, xy = TRUE)
names(x_df) <- c("x", "y", "value")
col1 <- c("red", "green")
g <- ggplot(data = x_df, aes(x, y,  fill = value)) +
  geom_tile()

現在我想將 colors 更改為 col1 中的那些。 我嘗試將colors = col1放在 ggplot aes 部分及其外部、geom_tile 中的 aes 以及其他一些選項中。 幾乎所有都返回錯誤消息Error: Aesthetics must be either length 1 or the same as the data (100): xxx

value轉換為因子解決了一個問題(圖例現在是離散的 0,1),但我仍然無法弄清楚在哪里添加代碼來更改默認的兩個 colors。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM