我有一个 struct 如下的数据框:

  x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 proportion index cumulative_proportion
1  0 -1  0  0  0 -1  1  1  0   1   0   0    0.28423     1               0.28423
2  0 -1  0  0  0 -1  1  1  1   1   0   0    0.20511     2               0.48934
3  1 -1  0  0  0 -1  1  1  0   1   0   0    0.05751     3               0.54685
4  0 -1  0  0  1 -1  1  1  0   1   0   0    0.02388     4               0.57073
5  0 -1  0  0  0 -1  1  1  0   1   1   0    0.02217     5               0.59290
6  0 -1  0  0  0 -1  1  1  0   1   0   1    0.02098     6               0.61388

我想使用geom_tile()进行可视化,其中var个变量在y轴上,x轴基于分类index,填充由变量是-1、0还是1来确定.问题是,同时,x轴应该显示cumulative_proportion变量,并且应该基于proportion来zoom 平铺.下面是一个非ggploy示例,其中的一些代码构建了一个非zoom 版本和示例数据框:

example

plot.df <- reshape2::melt(plot.df, id.vars=c("index", "proportion", "cumulative_proportion"))
ggplot(plot.df, aes(x=index, y=variable, fill=as.factor(value))) +
  geom_tile() 

example2

structure(list(x1 = c(0, 0, 1, 0, 0, 0, 1, 0, 0, 1), x2 = c(-1, 
-1, -1, -1, -1, -1, -1, -1, -1, -1), x3 = c(0, 0, 0, 0, 0, 0, 
0, 0, 0, 1), x4 = c(0, 0, 0, 0, 0, 0, 0, 1, 1, 0), x5 = c(0, 
0, 0, 1, 0, 0, 0, 0, 0, 0), x6 = c(-1, -1, -1, -1, -1, -1, -1, 
-1, -1, -1), x7 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), x8 = c(1, 
1, 1, 1, 1, 1, 1, 1, 1, 1), x9 = c(0, 1, 0, 0, 0, 0, 0, 0, 0, 
0), x10 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), x11 = c(0, 0, 0, 0, 
1, 0, 0, 0, 0, 0), x12 = c(0, 0, 0, 0, 0, 1, 1, 0, 1, 0), proportion = c(0.28423, 
0.20511, 0.05751, 0.02388, 0.02217, 0.02098, 0.0165, 0.01383, 
0.01185, 0.01013), index = 1:10, cumulative_proportion = c(0.28423, 
0.48934, 0.54685, 0.57073, 0.5929, 0.61388, 0.63038, 0.64421, 
0.65606, 0.66619)), row.names = c(NA, -10L), class = "data.frame")

推荐答案

一种 Select 是切换到geom_rect,这需要一些额外的数据处理来计算或设置矩形的位置:

library(ggplot2)
library(dplyr, warn = FALSE)

plot.df <- plot.df |>
  mutate(
    ymin = as.numeric(factor(variable)) - .5,
    ymax = as.numeric(factor(variable)) + .5
  ) |>
  mutate(
    xmin = lag(cumulative_proportion, default = 0),
    xmax = cumulative_proportion,
    .by = variable
  )

ggplot(plot.df, aes(y = variable, fill = as.factor(value))) +
  scale_y_discrete() +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), color = "white")

R相关问答推荐

使用预定值列表将模拟数量(n)替换为rnorm()

根据列表中项目的名称多次合并数据框和列表

R创建一个数据透视表,计算多个组的百分比

如何使用R中的dhrr函数将李克特量表的因子列从长转换为宽?

使用gggrassure减少地块之间的空间

在使用ggroove后,将图例合并在gplot中

如何将旋转后的NetCDF转换回正常的纬度/经度网格,并使用R?

在R中将特定列的值向右移动

将二进制数据库转换为频率表

ComplexHEAT:使用COLUMN_SPLIT时忽略COLUMN_ORDER

如何指定我的函数应该查找哪个引用表?

识别连接的子网(R-igraph)

在列表中排列R数据框中的列顺序

基于Key->Value数据帧的基因子集相关性提取

远离理论值的伽马密度曲线下面积的近似

生存时间序列的逻辑检验

在鼠标悬停时使用Plotly更改geom_point大小

有没有办法将勾选/审查标记添加到R中的累积关联图中?

带有Bootswatch Cerulean主题的shiny 仪表板中的浏览&按钮可见性问题

如何将数据框压缩为更宽,同时将行输入保持为行输入,而不是R中的列名?