【问题标题】:setting colors for geom_tile with both discrete and continuous variables使用离散变量和连续变量为 geom_tile 设置颜色
【发布时间】:2021-03-11 09:11:39
【问题描述】:

我正在使用 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))

【问题讨论】:

    标签: r ggplot2 geom-tile


    【解决方案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()) 
    

    【讨论】:

    • 谢谢,阿尔法正是我所追求的
    猜你喜欢
    • 2020-04-04
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多