对于OP的情况,我认为pivot_longer
是最好的。但是今天我遇到了一种似乎不适合旋转的情况,所以我使用以下代码以编程方式创建图层。我不需要使用eval()
.
data_tibble <- tibble(my_var = c(650, 1040, 1060, 1150, 1180, 1220, 1280, 1430, 1440, 1440, 1470, 1470, 1480, 1490, 1520, 1550, 1560, 1560, 1600, 1600, 1610, 1630, 1660, 1740, 1780, 1800, 1810, 1820, 1830, 1870, 1910, 1910, 1930, 1940, 1940, 1940, 1980, 1990, 2000, 2060, 2080, 2080, 2090, 2100, 2120, 2140, 2160, 2240, 2260, 2320, 2430, 2440, 2540, 2550, 2560, 2570, 2610, 2660, 2680, 2700, 2700, 2720, 2730, 2790, 2820, 2880, 2910, 2970, 2970, 3030, 3050, 3060, 3080, 3120, 3160, 3200, 3280, 3290, 3310, 3320, 3340, 3350, 3400, 3430, 3540, 3550, 3580, 3580, 3620, 3640, 3650, 3710, 3820, 3820, 3870, 3980, 4060, 4070, 4160, 4170, 4170, 4220, 4300, 4320, 4350, 4390, 4430, 4450, 4500, 4650, 4650, 5080, 5160, 5160, 5460, 5490, 5670, 5680, 5760, 5960, 5980, 6060, 6120, 6190, 6480, 6760, 7750, 8390, 9560))
# This is a normal histogram
plot <- data_tibble %>%
ggplot() +
geom_histogram(aes(x=my_var, y = ..density..))
# We prepare layers to add
stat_layers <- tibble(distribution = c("lognormal", "gamma", "normal"),
fun = c(dlnorm, dgamma, dnorm),
colour = c("red", "green", "yellow")) %>%
mutate(args = map(distribution, MASS::fitdistr, x=data_tibble$my_var)) %>%
mutate(args = map(args, ~as.list(.$estimate))) %>%
select(-distribution) %>%
pmap(stat_function)
# Final Plot
plot + stat_layers
这个想法是你用你想要插入到 geom/stat 函数的参数来组织一个 tibble。每行应对应于+
您要添加到 ggplot 的图层。然后使用pmap
. 这会创建一个图层列表,您可以简单地将其添加到绘图中。