我正在嘗試在 x 軸上顯示點圖的 計數,如下所述:在 x 軸上顯示點圖的計數
library(ggplot2)
library(grid)
date = seq(as.Date("2016/1/5"), as.Date("2016/1/12"), "day")
value = c(11,11,12,12,13,14,14,14)
dat =data.frame(date = date, value = value)
### base plot
g <- ggplot(dat, aes(x = value)) geom_dotplot(binwidth = 0.8) coord_flip()
g # output to read parameter
### calculation of width and height of panel
current.vpTree()
seekViewport('panel.3-4-3-4')
real_width <- convertWidth(unit(1,'npc'), 'inch', TRUE)
real_height <- convertHeight(unit(1,'npc'), 'inch', TRUE)
### calculation of other values
height_coordinate_range <-diff(ggplot_build(g)$layout$panel_params[[1]]$y.range)
real_binwidth <- real_height / height_coordinate_range * 0.8 # 0.8 is the argument binwidth
num_balls <- real_width / 1.1 / real_binwidth # the number of stacked balls. 1.1 is expanding value.
g ylim(0, num_balls)
但是,在我看來,這real_width是指面板的寬度,而不是整個情節。當我使用時,這會導致計數刻度和點之間的錯位:
ggsave(g,
filename = "g.png",
path = getwd(),
device = "png",
height = real_height,
width = real_width,
units = "cm")
鑒于我想要一個 6cm x 6cm 的圖,我怎樣才能找出面板的尺寸,以便我可以使用面板尺寸來計算num_balls?
uj5u.com熱心網友回復:
這個故事的寓意是:在繪制情節之前,您無法準確知道面板的大小。但是,您可以通過從輸出維度中減去繪圖裝飾的維度來近似它。這種方法忽略了在現實中,圖形設備可能具有影響文本真實大小的“解析度”/“縮放”引數。這里的原因是,由于面板是“空”單元,因此在減去每個非空單元之后,它們會適應輸出維度剩下的任何內容。
library(ggplot2)
library(grid)
dat =data.frame(
date = seq(as.Date("2016/1/5"), as.Date("2016/1/12"), "day"),
value = c(11,11,12,12,13,14,14,14)
)
g <- ggplot(dat, aes(x = value)) geom_dotplot(binwidth = 0.8) coord_flip()
output_width <- unit(6, "cm")
output_height <- unit(6, "cm")
# Convert plot to gtable
gt <- ggplotGrob(g)
# Find panel
is_panel <- grep("panel", gt$layout$name)
panel_location <- gt$layout[is_panel,]
# Note: panel width / heights are 'null' units
gt$widths[panel_location$l]
#> [1] 1null
gt$heights[panel_location$t]
#> [1] 1null
# Get widths/heights of everything except the panel
width <- gt$widths[-panel_location$l]
height <- gt$heights[-panel_location$t]
# Calculate as output size - size of plot decoration
panel_height <- output_height - sum(height)
panel_width <- output_width - sum(width)
convertUnit(panel_height, "cm")
#> [1] 4.6283951674277cm
convertUnit(panel_width, "cm")
#> [1] 4.57547850076103cm
由reprex 包于 2022-02-24 創建(v2.0.1)
有一些方法可以固定面板的尺寸,這會使事情變得更容易,但這不是問題所在。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/436090.html
