作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在构建一个自定义 ggplot 主题,以标准化我生成的图表的外观和感觉。目标比这个最小的例子更复杂,所以我正在寻找一个通用的解决方案。我有几个主要目标:
我面临的挑战是,当结合这两个约束时,保存的图像将窗口内的 ggplot 图居中,这作为默认设置是有意义的,但在这种情况下看起来很糟糕。
我希望有一个通用的解决方案可以在我导出时左对齐 ggplot 面板。理想情况下,这也适用于多面图。
似乎使用 gridExtra、gtable、cowplot 和 egg 包中的一个或一些组合应该可以实现某些东西,但是在试验了几个小时之后我有点不知所措。有人知道我该怎么做吗?我的代码包含在下面。
这是生成的图像。如您所见,标题在底部左对齐,但 ggplot 本身水平居中。我也希望 ggplot 图左对齐。
图表输出:/image/5EM2c.png
library(ggplot2)
# Generate dummy data
x <- paste0("var", seq(1,10))
y <- LETTERS[1:10]
data <- expand.grid(X=x, Y=y)
data$Z <- runif(100, -2, 2)
# Generate heatmap with fixed aspect ratio
p1 <- ggplot(data, aes(X, Y, fill= Z)) +
geom_tile() +
labs(title = 'A Heatmap Graph') +
theme(aspect.ratio = 1)
# A text grob for the footer
figure_number_grob <- grid::textGrob('Figure 10',
x = 0.004,
hjust = 0,
gp = grid::gpar(fontsize = 10,
col = '#01A184'))
plot_grid <- ggpubr::ggarrange(p1,
figure_number_grob,
ncol = 1,
nrow = 2,
heights = c(1,
0.05))
# save it
png(filename = '~/test.png', width = 3000, height = 1500, res = 300, type = 'cairo')
print(plot_grid)
dev.off()
最佳答案
我能够找到满足我需求的解决方案,尽管它确实感觉有点老套。
核心思想:
这是我的代码:
library(ggplot2)
# Generate dummy data
x <- paste0("var", seq(1,10))
y <- LETTERS[1:10]
data <- expand.grid(X=x, Y=y)
data$Z <- runif(100, -2, 2)
# Generate heatmap WITHOUT fixed aspect ratio. I address this below
p1 <- ggplot(data, aes(X, Y, fill= Z)) +
geom_tile() +
labs(title = 'A Heatmap Graph')
# Extract the legend from our plot
legend = gtable::gtable_filter(ggplotGrob(p1), "guide-box")
plot_output <- gridExtra::arrangeGrob(
p1 + theme(legend.position="none"), # Remove legend from base plot
grid::rectGrob(gp=grid::gpar(col=NA)), # Add a spacer
legend, # Add the legend back
grid::rectGrob(gp=grid::gpar(col=NA)), # Add a spacer
nrow=1, # Format plots in 1 row
widths=grid::unit.c(unit(0.5, "npc"), # Plot takes up half of width
(unit(0.5, "npc") - legend$width) * 0.5, # Spacer width
legend$width, # Legend width
(unit(0.5, "npc") - legend$width) * 0.5)) # Spacer width
# A text grob for the footer
figure_number_grob <- grid::textGrob('Figure 10',
x = 0.004,
hjust = 0,
gp = grid::gpar(fontsize = 10,
col = '#01A184'))
plot_grid <- ggpubr::ggarrange(plot_output,
figure_number_grob,
ncol = 1,
nrow = 2,
heights = c(1,
0.05))
# save it
png(filename = '~/test.png', width = 3000, height = 1500, res = 300, type = 'cairo')
print(plot_grid)
dev.off()
这是输出图像:/image/rgzFy.png
关于r - 使用固定纵横比保存时左对齐 ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61214552/
我有一张 table 。我希望它的数据垂直和水平居中。 我使用了 align="center"valign="middle" ,但它没有用。
我是一名优秀的程序员,十分优秀!