有没有办法设置图例中 colored颜色 条相对于绘图大小的宽度/高度?考虑一下这个例子:

library(ggplot2)

# some data for plotting
x = rep(1:2,2)
y = rep(1:2,each = 2)
data = data.frame(x = x,y = y,val = 1:4)

#plot:
pp = ggplot(data) + 
  geom_raster(aes(x=x,y=y,fill = val)) +
  scale_fill_continuous(guide = guide_colorbar(barwidth = unit(4,'cm'))) + 
  theme(legend.direction = 'horizontal',legend.position = 'bottom')
pp

reprex package(v2.0.1)于2022-05-04创建

我想要的是使图例中 colored颜色 条的宽度(精确地)与绘图的宽度相匹配,使图例与绘图一样宽.现在,当我使用不同的绘图设备时,绘图和 colored颜色 栏的宽度比率会发生变化:例如,在RStudio绘图预览中,它们与使用RStudio的zoom 功能时不同,并且使用ggsave结果以另一个比率保存它们.

推荐答案

正如@benson23在 comments 中所建议的那样,@teunbrand对你的问题给出了一个非常好的答案:Set legend width to be 100% plot width.如果使用该代码,它将如下所示:

#plot:
pp = ggplot(data) + 
  geom_raster(aes(x=x,y=y,fill = val)) +
  scale_fill_continuous(guide = guide_colorbar(barwidth = unit(4,'cm'))) + 
  theme(legend.direction = 'horizontal',legend.position = 'bottom') 
pp

gt <- ggplotGrob(pp) 

# Extract legend
is_legend <- which(gt$layout$name == "guide-box")
legend <- gt$grobs[is_legend][[1]]
legend <- legend$grobs[legend$layout$name == "guides"][[1]]

# Set widths in guide gtable
width <- as.numeric(legend$widths[4]) # save bar width (assumes 'cm' unit) 
legend$widths[4] <- unit(1, "null") # replace bar width

# Set width/x of bar/labels/ticks. Assumes everything is 'cm' unit.
legend$grobs[[2]]$width <- unit(1, "npc")
legend$grobs[[3]]$children[[1]]$x <- unit(
  as.numeric(legend$grobs[[3]]$children[[1]]$x) / width, "npc"
)
legend$grobs[[5]]$x0 <- unit(as.numeric(legend$grobs[[5]]$x0) / width, "npc")
legend$grobs[[5]]$x1 <- unit(as.numeric(legend$grobs[[5]]$x1) / width, "npc")

# Replace legend
gt$grobs[[is_legend]] <- legend

# Draw new plot
grid::grid.newpage()
grid::grid.draw(gt)

输出:

enter image description here

R相关问答推荐

使用R中的gt对R中的html rmarkdown文件进行条件格式设置表的单元格

管道末端运行功能

为什么在ggplot2中添加geom_text这么慢?

使用strsplit()将向量操作为数据框

多个过滤器内的一个盒子在仪表板Quarto

对于变量的每个值,仅 Select 包含列表中所有值的值.R

如何在分组条形图中移动相关列?

如何删除最后一个可操作对象

Data.table';S GForce-将多个函数应用于多列(带可选参数)

汇总数据的Sheffe检验的P值(平均值和标准差)

如何根据R中其他变量的类别汇总值?

将标识符赋给事件序列,避免错误观察

提高圣彼得堡模拟的速度

ggplot R:X,Y,Z使用固定/等距的X,Y坐标绘制六边形热图

层次树图的数据树

错误包arrowR:READ_PARQUET/OPEN_DATASET&QOT;无法反序列化SARIFT:TProtocolException:超出大小限制&Quot;

名字的模糊匹配

使用&Fill&Quot;在gglot中创建 colored颜色 渐变

从字符串01JAN2021创建日期

只有当我在循环的末尾放置一条print语句时,Foreach才会给出预期的输出