簡體   English   中英

ggplot geom_rect 顏色漸變(不參考數據)?

[英]ggplot geom_rect color gradient (without reference to data)?

我想知道是否有可能在沒有數據參考的情況下使用帶有顏色漸變的 geom_rect,即在 aes() 之外。 我希望以下 plot 底部的兩個矩形顯示從紅色到白色(從左到右)的顏色漸變,頂部的一個顯示從黃色到白色的顏色漸變。 這是否可以通過簡單的方式實現,還是我必須創建數據來引用?

ggplot() +
  geom_rect(aes(xmin = c(1, 3), xmax = c(2.5, 4), ymin = c(1, 1), ymax = c(2, 2)), color = "black", fill = "red") +
  geom_rect(aes(xmin = 1, xmax = 3.5, ymin = 3, ymax = 4), color = "black", fill = "yellow") +
  theme_bw() +
  theme(panel.grid = element_blank())

在此處輸入圖像描述

我嘗試將scale_fill_gradientgeom_tile一起使用,但這並沒有真正達到我想要的效果:1.兩個應該是紅色的矩形共享一個漸變,並且每個都不是以純紅色開始,2.我無法管理在一個 plot 中使用兩個不同的scale_fill_gradient

foo <- tibble(x = seq(from = 1, to = 2.5, by = 0.001),
              y = rep(1, 1501))
bar <- tibble(x = seq(from = 3, to = 4, by = 0.001),
              y = rep(1, 1001))
foobar <- tibble(x = seq(from = 1, to = 3.5, by = 0.001),
              y = rep(3, 2501))

ggplot() +
  geom_tile(data = foo, aes(x = x, y = y, fill = x)) +
  geom_tile(data = bar, aes(x = x, y = y, fill = x)) +
  scale_fill_gradient(low = 'red', high = 'white') +
  geom_tile(data = foobar, aes(x = x, y = y, fill = x)) +
  scale_fill_gradient(low = 'yellow', high = 'white') +
  theme_bw() +
  theme(panel.grid = element_blank())

在此處輸入圖像描述

您可以在 plot 過程中的兩個不同scale_fill_gradient函數之間使用來自ggnewscale的 function new_scale_fill 這將重置您的美學,以便可以使用像這樣的另一個漸變:

library(tibble)
foo <- tibble(x = seq(from = 1, to = 2.5, by = 0.001),
              y = rep(1, 1501))
bar <- tibble(x = seq(from = 3, to = 4, by = 0.001),
              y = rep(1, 1001))
foobar <- tibble(x = seq(from = 1, to = 3.5, by = 0.001),
                 y = rep(3, 2501))

library(ggplot2)
library(ggnewscale)
ggplot() +
  geom_tile(data = foo, aes(x = x, y = y, fill = x)) +
  geom_tile(data = bar, aes(x = x, y = y, fill = x)) +
  scale_fill_gradient(low = 'red', high = 'white') +
  new_scale_fill() +
  geom_tile(data = foobar, aes(x = x, y = y, fill = x)) +
  scale_fill_gradient(low = 'yellow', high = 'white') +
  theme_bw() +
  theme(panel.grid = element_blank())

使用reprex v2.0.2創建於 2022-09-23


要為每個geom_tile添加漸變顏色,您可以像這樣為每個 tile new_scale_fill使用:

library(ggplot2)
library(ggnewscale)
ggplot() +
  geom_tile(data = foo, aes(x = x, y = y, fill = x)) +
  scale_fill_gradient(low = 'red', high = 'white', guide = 'none') +
  new_scale_fill() +
  geom_tile(data = bar, aes(x = x, y = y, fill = x)) +
  scale_fill_gradient(low = 'red', high = 'white') +
  new_scale_fill() +
  geom_tile(data = foobar, aes(x = x, y = y, fill = x)) +
  scale_fill_gradient(low = 'yellow', high = 'white') +
  theme_bw() +
  theme(panel.grid = element_blank())

使用reprex v2.0.2創建於 2022-09-23

暫無
暫無

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

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