使用离散变量和连续变量为 geom_tile 设置颜色
setting colors for geom_tile with both discrete and continuous variables
我正在使用 ggplot 中的 geom_tile 函数来可视化一些空间数据。我有一个连续变量 region_relative_rainfall
和一个离散变量 region
。我想为离散变量的每个级别创建一个具有对比色的清晰图。并且在离散变量的每个级别内,连续变量具有相同的颜色顺序。我只知道如何更改填充和颜色,如下面的代码所示,但并不像我想的那么清楚。任何提示将不胜感激。
# geom_tile question
library(ggplot2)
library(dplyr)
set.seed(123)
n_row = 10
n_col = 20
df = expand.grid(1:n_row, 1:n_col)
colnames(df) = c("y","x")
n = n_row * n_col
k = 5
df$region = sample(x = letters[1:k], size = n, replace = T)
df$rainfall = rlnorm(n = n, log(13), 0.4)
## normalise rainfall by region, to sum = 1 for each region
df <- df %>%
group_by(region) %>%
mutate("region_relative_rainfall" =rainfall / sum(rainfall))
## Current plot, not quite what I want
ggplot(df, aes(x = x, y = y, fill = region_relative_rainfall, color = region)) +
geom_tile() +
theme(panel.grid = element_blank(),
axis.text = element_blank()) +
scale_y_reverse( lim=c(n_row,1))
你需要这样的东西吗?
library(ggplot2)
ggplot(df) + aes(x = x, y = region, fill = region) +
geom_tile(aes(alpha = region_relative_rainfall)) +
theme(panel.grid = element_blank(),
axis.text = element_blank())
我正在使用 ggplot 中的 geom_tile 函数来可视化一些空间数据。我有一个连续变量 region_relative_rainfall
和一个离散变量 region
。我想为离散变量的每个级别创建一个具有对比色的清晰图。并且在离散变量的每个级别内,连续变量具有相同的颜色顺序。我只知道如何更改填充和颜色,如下面的代码所示,但并不像我想的那么清楚。任何提示将不胜感激。
# geom_tile question
library(ggplot2)
library(dplyr)
set.seed(123)
n_row = 10
n_col = 20
df = expand.grid(1:n_row, 1:n_col)
colnames(df) = c("y","x")
n = n_row * n_col
k = 5
df$region = sample(x = letters[1:k], size = n, replace = T)
df$rainfall = rlnorm(n = n, log(13), 0.4)
## normalise rainfall by region, to sum = 1 for each region
df <- df %>%
group_by(region) %>%
mutate("region_relative_rainfall" =rainfall / sum(rainfall))
## Current plot, not quite what I want
ggplot(df, aes(x = x, y = y, fill = region_relative_rainfall, color = region)) +
geom_tile() +
theme(panel.grid = element_blank(),
axis.text = element_blank()) +
scale_y_reverse( lim=c(n_row,1))
你需要这样的东西吗?
library(ggplot2)
ggplot(df) + aes(x = x, y = region, fill = region) +
geom_tile(aes(alpha = region_relative_rainfall)) +
theme(panel.grid = element_blank(),
axis.text = element_blank())