我已經使用“knitr”包編織了一個 PDF。它還使用“ggsave”將 PNG 檔案保存在目錄中。
- 當從塊中手動生成 PNG 檔案時
- 條形圖:PNG 檔案大小為 13.3 kb,尺寸為 1008 x 1008。
- 編織程序中生成PNG檔案時,使用“Ctrl Shift K”
- 條形圖:PNG 檔案大小為 11.4 kb,尺寸為 936 x 647。
我應該怎么做才能使兩種情況下生成的 PNG 檔案具有相同的大小和尺寸?如果可能的話,我希望在這兩種情況下輸出都是 13.3 kb。
我添加了最小可重現示例的代碼。請將其保存為“.Rmd”檔案以生成 PNG 和 PDF。
謝謝你
- 用于生成 PDF 的檔案的 YAML 標頭(用三連字符包圍)
title: "Image Size Mismatch"
output: pdf_document
- 用于加載包、生成條形圖并將其保存為 PNG 的 R 代碼。
編輯:較小的代碼示例
# Packages
library("knitr")
library("ggplot2")
# Data
hh <- data.frame(groups = factor(c("No", "Yes", NA)), n = c(3843, 856, 19))
# Create Chart
pp <- ggplot(data = hh, aes(x = groups, y = n)) geom_bar(stat = 'identity')
# Save Image
ggsave("Bar.png", plot = pp, device = "png", dpi = 144)
較早的示例:它有一些不必要的代碼。
# Packages
library("knitr")
library("dplyr")
library("tibble")
library("ggplot2")
# Data
hh <- tibble(groups = factor(c("No", "Yes", NA)), n = c(3843, 856, 19))
loc_png <- "Pie.png"
# Create Pie Chart
pp <- ggplot(data = hh, aes(x = '', y = n, fill = groups))
geom_bar(stat = 'identity', width = 1, color = "white")
coord_polar(theta = "y", start = 0)
# Add Text Labels
geom_text(aes(label = paste0(groups, "\n", n)),
position = position_stack(vjust = 0.5))
# Theme and Labs
theme(panel.background = element_rect(fill = "white", colour = "white"),
legend.position = 'none', axis.text = element_blank(),
axis.ticks = element_blank(), axis.title = element_blank(),
panel.grid = element_blank())
labs(title = "Pie")
# Save Image
ggsave(loc_png, plot = pp, device = "png", dpi = 144)
# Problem:
# Manual Chunk Execution: Output File: Size 32.5 kb, Dimension 1008 x 1008
# Knit "Ctrl Shift K" : Output File: Size 22.4 kb, Dimension 936 x 647
uj5u.com熱心網友回復:
您可以控制在 RMarkdown 和ggsave. 出于您的目的,您需要將兩者設定為相同的值。
https://bookdown.org/yihui/rmarkdown-cookbook/figure-size.html中描述了調整繪圖大小從而調整縱橫比,正確使用ggsavein help("ggsave")。
以下最小示例是有效的 Rmd 并使用同一檔案中的兩個選項:
---
title: "Untitled"
output: pdf_document
---
```{r, fig.dim = c(5, 3)}
library(ggplot2)
ggplot(iris)
geom_point(aes(x = Sepal.Length, y = Sepal.Width))
ggsave("test.png", width = 5, height = 3, units = "in")
```
老實說,我不知道針織檔案中使用了多少每英寸點數 (dpi),我的示例似乎是作為矢量檔案撰寫的,但如果需要,也可以在ggsave. 成為ggsaveRmd 內部或外部的呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/471344.html
下一篇:無標簽影像分割
