如何为ggridges曲线下方区域着色并高亮多图中20℃以上温度区域
Solution for Coloring Ggridges and Highlighting Temperatures Above 20℃
Got it, let's tackle your two visualization requirements step by step. Here are two practical approaches to achieve both coloring the area under the ggridges curves and highlighting regions where temperature exceeds 20℃:
Approach 1: Overlay a Highlight Layer
This method uses a base colored ridge line and adds a separate red fill layer for temperatures above 20℃, making the high-temperature region stand out clearly.
library(tidyverse) library(ggridges) library(lubridate) # For date processing (if needed) # First, ensure your dataset has a `year` column (extract from Date if not present) t2 <- t2 %>% mutate(year = year(ym(Date))) ggplot(t2, aes(x = t, y = year)) + # Base density ridges with solid fill stat_density_ridges( geom = "density_ridges_gradient", quantile_lines = TRUE, quantiles = 2, fill = "lightsteelblue", # Base fill color alpha = 0.7 # Adjust transparency to let highlight show through ) + # Highlight region where temperature >20℃ stat_density_ridges( geom = "area", fill = "firebrick", alpha = 0.5, # Transparent red to avoid covering base layer data = . %>% filter(t > 20), # Only use data points above 20℃ scale = 1, # Match scale with base ridges position = "identity" ) + theme_ridges() + labs(x = "Temperature (℃)", y = "Year")
Key Notes:
- The first
stat_density_ridgescreates the base colored area under the curves. - The second
stat_density_ridgesfilters for temperatures above 20℃ and draws a red fill layer on top, aligned with the base ridge lines.
Approach 2: Conditional Fill in a Single Layer
This method uses conditional coloring within the same ridge layer, splitting the fill color based on whether the temperature is above or below 20℃.
library(tidyverse) library(ggridges) library(lubridate) t2 <- t2 %>% mutate(year = year(ym(Date))) ggplot(t2, aes(x = t, y = year)) + stat_density_ridges( geom = "density_ridges_gradient", quantile_lines = TRUE, quantiles = 2, aes(fill = stat(x > 20)), # Map fill to temperature condition alpha = 0.8 ) + # Customize fill colors and legend scale_fill_manual( values = c("lightsteelblue", "firebrick"), labels = c("≤ 20℃", "> 20℃"), name = "Temperature Range" ) + theme_ridges() + labs(x = "Temperature (℃)", y = "Year")
Key Notes:
stat(x > 20)uses the computed density x-values to apply conditional coloring directly in the ridge layer.- The legend clearly distinguishes the two temperature ranges, making the visualization more informative.
内容的提问来源于stack exchange,提问作者ixodid
相关产品推荐
相关产品推荐

