按组手动填充多个比例的geom_tile

2024-04-25

I have the following current output:

我的目标是像这样的着色,但只填充到最大级别(例如填充停止在当前级别):

创建此数据的数据是:

df <- tribble(~Question_Code,   ~RespondentLevel,
"Engagement - Inclusion",   5,
"External engagement - policies",   2,
"External engagement - technology", 5,
"Community data ",  5,
"Internal engagement",  5,
"Internal use of technology",   4,
"Familiarity/Alignment",    5,
"Environmental impacts",    5,
"Innovation",   2,
"Use of open-source technology",    2,
"Regulation of hardware & software",    5,
"In-house technical capacity",  5,
"Infrastructure procurement",   5,
"Algorithmic Error & Bias", 2,
"Control: Privacy", 5,
"Accountability in Governance Structures",  3,
"Open procurement", 5,
"Use in decision-making",   1,
"Accountability",   1,
"External Control", 4,
"Internal Control", 2,
"Open Data",    2)
levels <-  c("Open Data","Internal Control","External Control","Accountability",
             "Use in decision-making","Open procurement","Accountability in Governance Structures","Control: Privacy",
             "Algorithmic Error & Bias","Infrastructure procurement","In-house technical capacity",
             "Regulation of hardware & software","Use of open-source technology","Innovation",
             "Environmental impacts","Familiarity/Alignment",
             "Internal use of technology","Internal engagement","Community data",
             "External engagement - technology","External engagement - policies","Engagement - Inclusion")

df <- df %>% mutate(Domain = c(as.character((rep("Domain 1", 5))),
                  as.character(rep("Domain 2", 4)),
                  as.character(rep("Domain 3", 6)),
                  as.character(rep("Domain 4", 7))))

对于 ggplot:

df %>% 
ggplot(aes(x = RespondentLevel, y = fct_rev(Question_Code))) +
  geom_tile() +
  theme_minimal(16)

我正在使用的填充颜色:

with each colour corresponding to a domain, and each shade to a level:
Greens <- c("#edf8e9", "#bae4b3", "#74c476", "#31a354", "#006d2c")

Reds <- c("#fee5d9", "#fcae91", "#fb6a4a", "#de2d26", "#a50f15")

Yellows <- c("#ffffeb","#ffff9d","#ffff89", "#ffff4e", "#ffff14")

Blues <- c("#eff3ff","#bdd7e7","#6baed6","#3182bd",  "#08519c")

编辑:geom_bar 也可以做到这一点,但没有按梯度分解。尝试使用这个功能 https://stackoverflow.com/questions/49818271/stacked-barplot-with-colour-gradients-for-each-bar:

ColourPalleteMulti <- function(df, group, subgroup){

  # Find how many colour categories to create and the number of colours in each
  categories <- aggregate(as.formula(paste(subgroup, group, sep="~" )), df, function(x) length(unique(x)))
  category.start <- (scales::hue_pal(l = 100)(nrow(categories))) # Set the top of the colour pallete
  category.end  <- (scales::hue_pal(l = 40)(nrow(categories))) # set the bottom

  # Build Colour pallette
  colours <- unlist(lapply(1:nrow(categories),
                           function(i){
                             colorRampPalette(colors = c(category.start[i], category.end[i]))(categories[i,2])}))
  return(colours)
}

colours <- ColourPalleteMulti(df, "Domain", "RespondentLevel") 
df %>% 
  ggplot(aes(x = fct_rev(Question_Code), y = RespondentLevel))+
  geom_bar(stat = "identity", aes(fill = Domain), alpha = .9) +
  coord_flip() +
  theme_minimal(16)+
  xlab(" ") +
  ggtitle("Baseline Report Card Sample Community")+
  scale_fill_manual("RespondentLevel", values = colours)+
  theme(legend.title = element_text(size = 14),
        legend.position = "none",
        legend.text = element_text(size = 14),
        plot.title = element_text(size=18, hjust = 0.5),
        plot.caption = element_text(size = 12, hjust = 1),
        axis.text.y = element_text(hjust = 0),
        panel.grid = element_line(colour = "#F0F0F0"),
        plot.margin = unit(c(1,1,0.5,1), "cm"))

抱歉长篇大论,如果可能的话可以调整


这里有一些技巧选项。首先,为了获得每个问题的完整级别,这样数据中就不会出现空白,我使用了tidyr::complete。这就是我将要使用的数据框。

library(ggplot2)
library(dplyr)
library(tidyr)
library(purrr)
library(patchwork)

df_full <- df %>%
  complete(nesting(Domain, Question_Code), RespondentLevel) %>%
  mutate(RespondentLevel = as.character(RespondentLevel)) 

更简单的选择是通过更改 alpha 来近似渐变,并根据域设置色调(红色、绿色等)。这会放弃您选择的其他颜色,而仅使用每个调色板中最后一个最暗的颜色。

为此,我列出了所有调色板。在设置填充时,map_chr(palettes, 5)提取每个列表的第 5 个元素,它是每个列表中最暗的颜色。您可能需要调整或删除一个或两个图例。

palettes <- list(Greens, Reds, Yellows, Blues)

ggplot(df_full, aes(x = RespondentLevel, y = Question_Code, fill = Domain, alpha = RespondentLevel)) +
  geom_tile() +
  theme_minimal() +
  facet_grid(rows = vars(Domain), scales = "free", space = "free") +
  scale_fill_manual(values = map_chr(palettes, 5))
#> Warning: Using alpha for a discrete variable is not advised.

更困难的方法是按域分割数据并制作一个图列表,然后将它们与patchwork包裹。好处是您可以保留完整的调色板,但缺点是更难以控制您从中获得的尺寸等内容facet_grid,它根据以下事实进行调整:某些域中列出的问题多于其他域中列出的问题。您可以手动调整它们的大小plot_layout如果您认为这种方法值得。您还需要调整一些主题元素来模仿facet_grid会做。

plot_list <- df_full %>%
  split(.$Domain) %>%
  map2(palettes, function(domain_df, pal) {
    ggplot(domain_df, aes(x = RespondentLevel, y = Question_Code, fill = RespondentLevel)) +
      geom_tile() +
      theme_minimal() +
      scale_fill_manual(values = pal) +
      theme(legend.position = "none") +
      labs(x = NULL, y = NULL)
  })

reduce(plot_list, `+`) +
  plot_layout(ncol = 1)

请注意,通常情况下,patchwork将图放在一起,就像plot1 + plot2模仿ggplot分层。由于我在列表中包含了绘图,所以我这样做了purrr::reduce.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按组手动填充多个比例的geom_tile 的相关文章

  • R 笔记本:opts_chunk 没有效果

    我正在开发我的第一台 R 笔记本 除了一个问题之外 它运行得很好 我想成为我内联输出的数字 r realbignumber 以逗号作为分隔符且最多 2 位小数 123 456 789 12 为了实现这一目标 我在文档的开头添加了一个块 其中
  • ggplot2:从纵横比中排除图例

    I use ggplot2 and knitr发布带有右侧图例的散点图 图例包含在纵横比中 因此破坏了绘图的 方形 如图所示默认主题 https github com hadley ggplot2 wiki themes 当图例文本变得比
  • 删除 ggplot 地图/choropleth 中的边框线

    我想删除 ggplot 中生成的等值线区域之间的线 我的问题是由一张非常大的地图引起的 其中包含非常非常小的区域 人口普查区块组 这些区域数量如此之多 以至于鉴于边界的密度 不可能看到填充形状的颜色 我在 Mac 上使用更新后的 RStud
  • 在 R 闪亮应用程序中接受 HTTP 请求

    我制作了一个闪亮的应用程序 需要从另一台服务器获取其数据 即打开闪亮的应用程序时 另一台服务器向闪亮的应用程序发送请求以打开应用程序并向其提供所需的数据 为了模拟这一点 当我在 Firefox 中打开 R闪亮应用程序时 我可以将以下内容发送
  • 使用R中的XLSX包在Excel中打印data.frame时出错

    数据框是可见的 没有任何错误 但是 当使用 XLSX 包的 write xlsx 函数打印相同内容时 会出现错误 Error in jcall cell V setCellValue value method setCellValue wi
  • 多维数组到数据框

    R 中的以下问题对你们中的许多人来说可能看起来很简单 但由于我对此相对较新 如果您能帮助我 那将非常有帮助 我想本质上编写一个多维 3 个维度 数组作为我可以更轻松地操作的数据框 我正在处理 1891 年 1 月 1 日至 2015 年 1
  • data.table 逐行求和、平均值、最小值、最大值,如 dplyr?

    还有其他关于数据表上的行式运算符的帖子 他们要么是太简单 https stackoverflow com questions 7885147 efficient row wise operations on a data table或解决一
  • 使用 R 实现具有不同距离度量的 KNN

    我正在研究一个数据集 以便比较不同距离度量的效果 我正在使用KNN算法 R中的KNN算法默认使用欧几里德距离 所以我写了自己的一个 我想找到最近邻居和目标之间正确的类标签匹配的数量 我一开始就准备好了资料 然后我调用数据 wdbc n 我选
  • 对整数进行反直觉测试:63 = (45 x 1.4) = 62

    我写了一个 可能不是特别好 函数来测试一个数字是否是整数 is wholeNumber lt function x x floor x 一般来说 这个函数对我的目的来说效果很好 因为我实际上只考虑用少数小数位测试数字的情况 所以我天真的理解
  • ShinyApp:由对等方重置连接

    我之前构建的闪亮应用程序在我的旧笔记本电脑上运行良好 最近我买了一台装有Windows10的新笔记本电脑 设置完所有内容后 我尝试运行该应用程序 但浏览器立即打开并关闭 并出现错误 正在收听http 127 0 0 1 5004 http
  • ANEW 字典可以用于 Quanteda 中的情感分析吗?

    我正在尝试找到一种方法来实施英语单词情感规范 荷兰语 以便使用 Quanteda 进行纵向情感分析 我最终想要的是每年的 平均情绪 以显示任何纵向趋势 在数据集中 所有单词均由 64 名编码员按照 7 分李克特量表在四个类别上进行评分 这提
  • 使用鼠标功能时出错:没有什么可以估算的

    我尝试将 NA 数据填充到数据框中 我做了简单的数据 library mice first lt c 1 2 3 4 5 NA 7 8 9 NA second lt c 1 2 NA 4 5 6 7 NA 9 10 sample data
  • 使用 Caret 包的测试集的 ROC 曲线

    我正在尝试从测试集上的插入符号中获取最佳模型的 ROC 曲线 我碰到MLeval包似乎很方便 输出非常全面 使用几行代码提供了所有需要的指标和图表 一个很好的例子在这里 https stackoverflow com a 59134729
  • R/ggplot2:在执行 ylim 上限的同时平滑整个数据集

    更新 我找到了答案 包含在下面 我有一个包含以下变量和类似值的数据集 COBSDATE CITY RESPONSE TIME 2011 11 23 A 1 1 2011 11 23 A 1 5 2011 11 23 A 1 2 2011 1
  • 向图节点添加标签

    我使用 visnetwork 库制作了下图 library tidyverse library igraph set seed 123 n 15 data data frame tibble d paste 1 n relations da
  • 如何在R中使用twoord.plot()绘制多个图(分面)?

    我的数据看起来像这样 height lt c 1 2 3 4 2 4 6 8 weight lt c 12 13 14 15 22 23 24 25 person lt c Jack Jim Jill Tess Jack Jim Jill
  • 如何访问/记住闪亮中未选中的值?

    我正在摆弄 R 中的闪亮应用程序 该应用程序有 选择列表Input A 主要组 具有可能的值 A B 和 或C 一组复选框Input b 子群 它们是 通过选择动态填充Input A列表 chkb a 和 chkb b 代表 A c d 代
  • 在 R 中连接/匹配数据帧

    我有两个数据框 第一列有两列 x是水深 y是每个深度的温度 第二个也有两列 x也是水深 但与第一个表中的深度不同 第二栏z是盐度 我想通过以下方式连接两个表x 通过增加z到第一张桌子 我已经学会了如何使用 key 来连接表tidyr 但只有
  • 使用 dplyr 按行用以前的值填充缺失值

    我正在使用 R 中的一个数据框 该数据框跨行有一些缺失值 数据框是下一个 dput添加到最后 df id V1 V2 V3 V4 1 01 1 1 1 NA 2 02 2 1 NA NA 3 03 3 1 NA NA 4 04 4 1 2
  • 如何在 R 中验证日期

    我有一个格式为的日期dd mm yyyy HH mm ss验证该日期的最佳和最简单的方法是什么 I tried d lt format Date date format d m Y H M S 但是当非法日期过去时如何捕获错误呢 简单的方法

随机推荐