[英]Tidy up coefficient plot
在下面的系數 plot 中,我想減少“道路”和“時間”下的空白區域,以紅色突出顯示:
我怎樣才能讓這個看起來更整潔? 以下是我當前的代碼,使用 ggplot2:
plotdata <- structure(
list(
term = c("Category 1_a","Category 1_b","Category 1_c","Category 1_d","Category 2",
"Category 3_a","Category 3_b"),
estimate = c(-0.033882004,0.001508041,0.122957935,-0.033882004,0.001508041,-0.033882004,0.001508041),
ymin = c(
-0.13278953,-0.007547426,0.025116265,-0.13278953,-0.007547426,-0.13278953,-0.007547426), ymax = c(0.065025521,0.010563508,0.220799605,0.065025521,0.010563508,0.065025521,0.010563508)
), row.names = c(NA,-7L),
spec = structure(list(cols = list(
term = structure(list(), class = c("collector_character",
"collector")),
estimate = structure(list(), class = c("collector_double",
"collector")),
ymin = structure(list(), class = c("collector_double",
"collector")),
ymax = structure(list(), class = c("collector_double",
"collector"))
),
default = structure(list(), class = c("collector_guess",
"collector")),
delim = ","), class = "col_spec"),class = c("spec_tbl_df","tbl_df", "tbl", "data.frame"))
# Libraries
library(dplyr)
library(broom)
library(ggplot2)
# Plot
plotdata %>%
mutate(category = rep(c("Pollution", "Roads", "Timing"), times = c(4, 1, 2))) %>%
mutate(term = factor(term, levels = rev(term))) %>%
ggplot(aes(x = term, y = estimate)) +
geom_hline(yintercept = 0, color="black", size = 0.5, linetype = "dashed") +
geom_pointrange(aes(ymin = ymin, ymax = ymax), size = 0.5,
fill="#0202fe", color="#b5b5b5", shape=21, stroke = 1) +
labs(x = NULL, y = "Coefficient Estimate") +
scale_x_discrete(expand = c(0.4, 0.1)) +
coord_flip() +
facet_grid(category~., switch = 'y', scales = 'free_y') +
theme_classic(base_size = 13) +
theme(strip.placement = 'outside',
strip.background = element_blank(),
strip.text.y.left = element_text(face = 'bold', angle = 0, vjust = 1, hjust = 1),
panel.spacing.y = unit(0, 'mm'))
這可以通過facet_grid
的space
參數來實現。 設置space="free_y"
會根據“與y標尺長度成正比”設置面板大小,即類別個數:
注意:我還刪除了scale_x_discrete
。
library(dplyr)
library(broom)
library(ggplot2)
# Plot
plotdata %>%
mutate(category = rep(c("Pollution", "Roads", "Timing"), times = c(4, 1, 2))) %>%
mutate(term = factor(term, levels = rev(term))) %>%
ggplot(aes(x = term, y = estimate)) +
geom_hline(yintercept = 0, color="black", size = 0.5, linetype = "dashed") +
geom_pointrange(aes(ymin = ymin, ymax = ymax), size = 0.5,
fill="#0202fe", color="#b5b5b5", shape=21, stroke = 1) +
labs(x = NULL, y = "Coefficient Estimate") +
coord_flip() +
facet_grid(category~., switch = 'y', scales = 'free_y', space = "free_y") +
theme_classic(base_size = 13) +
theme(strip.placement = 'outside',
strip.background = element_blank(),
strip.text.y.left = element_text(face = 'bold', angle = 0, vjust = 1, hjust = 1),
panel.spacing.y = unit(0, 'mm'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.