r - 每组ggridges颜色渐变
问题描述
我正在尝试制作包含两组和每组内的颜色渐变的山脊线图。例如,工会主义者从深蓝色到浅蓝色,印地集团从深红色到浅红色。
提前致谢!
library(dplyr)
library(forcats)
Catalan_elections %>%
mutate(YearFct = fct_rev(as.factor(Year))) %>%
ggplot(aes(y = YearFct)) +
geom_density_ridges(
aes(x = Percent, fill = paste(YearFct, Option)),
alpha = .8, color = "white", from = 0, to = 100
) +
labs(
x = "Vote (%)",
y = "Election Year",
title = "Indy vs Unionist vote in Catalan elections",
subtitle = "Analysis unit: municipalities (n = 949)",
caption = "Marc Belzunces (@marcbeldata) | Source: Idescat"
) +
scale_y_discrete(expand = c(0.01, 0)) +
scale_x_continuous(expand = c(0.01, 0)) +
scale_fill_cyclical(
breaks = c("1980 Indy", "1980 Unionist"),
labels = c(`1980 Indy` = "Indy", `1980 Unionist` = "Unionist"),
values = c("#ff0000", "#0000ff", "#ff8080", "#8080ff"),
name = "Option", guide = "legend"
) +
theme_ridges(grid = FALSE)
解决方案
我没有Catalan_elections
数据,所以我将尝试提供一个带有虚拟数据的最小示例。
fill
要将多个变量映射到不同的尺度,您可以使用该ggnewscale
包。权衡是您必须geom_density_ridges_gradient
为每个映射单独调用。
library(ggplot2)
library(ggridges)
#>
#> Attaching package: 'ggridges'
#> The following object is masked from 'package:ggplot2':
#>
#> scale_discrete_manual
library(ggnewscale)
df <- data.frame(
x = c(rnorm(100, -2), rnorm(100, 2)),
y = rep(LETTERS[1:2], each = 100)
)
ggplot(df, aes(x, y)) +
geom_density_ridges_gradient(data = df[df$y == "A", ],
aes(fill = stat(x)), scale = 1) +
scale_fill_gradient(low = "lightblue", high = "darkblue",
name = "A") +
# Note that a fill scale must exist already before a new one can be used
new_scale_fill() +
geom_density_ridges_gradient(data = df[df$y == "B", ],
aes(fill = stat(x)), scale = 1) +
scale_fill_gradient(low = "lightcoral", high = "darkred",
name = "B")
#> Picking joint bandwidth of 0.324
#> Picking joint bandwidth of 0.343
由reprex 包(v0.3.0)于 2019 年 12 月 3 日创建
我相信将此示例扩展到您自己的数据不会太难。
推荐阅读
- reactjs - 如何使用 zustand 将对象键设置为状态
- reactjs - 使用 i18next 翻译问题
- r - R:在变量列表中使用 gam::gam 和 lapply
- java - 在 SoapFault 或异常中弹簧捕获肥皂请求
- java - 无法在网页抓取中选择类标签的内容
- xml - Idnentity transform XSLT - remove special characters
- delphi - 在悉尼,在物体前设置 [弱] 会受到惩罚吗?
- google-apps-script - https://drive.google.com 的 Google 表格宏错误请求失败,返回代码 403
- huawei-mobile-services - 如果我的快应用被拒绝,并且错误信息提示发生错误,我该怎么办?
- windows - 使用 Powershell 编辑注册表项