gpt4 book ai didi

r - 在ggplot中拆分y轴

转载 作者:行者123 更新时间:2023-12-04 11:42:12 27 4
gpt4 key购买 nike

我的数据结构类似于以下结构:

data.frame(x = c("A", "B", "C", "D", "E"), 
a = abs(rnorm(5)),
b = abs(rnorm(5)))

我想以以下方式显示它(请原谅糟糕的油漆工作):
Example

为此,我编写了以下代码:
set.seed(20)
data.frame(x = c("A", "B", "C", "D", "E"),
a = abs(rnorm(5)),
b = abs(rnorm(5))) %>%
mutate(b = -b) %>%
gather("source", "amount", a, b) %>%
ggplot(aes(x = x,
y = amount,
fill = source)) +
geom_col() +
scale_y_continuous(labels = abs)

这给了我以下内容:

Result

我将如何沿 y = 0 添加间隙并用 x 轴标签填充它?

最佳答案

我们可以通过将它们移动到 facet 来获得大部分方法:

set.seed(20)
data.frame(x = c("A", "B", "C", "D", "E"),
a = abs(rnorm(5)),
b = abs(rnorm(5))) %>%
mutate(b = -b) %>%
gather("source", "amount", a, b) %>%
ggplot(aes(x = x,
y = amount,
fill = source)) +
geom_col() +
scale_y_continuous(labels = abs) +

# NEW STUFF:
facet_wrap(~source, ncol=1, scales = "free_y") +
theme(strip.text = element_blank())

enter image description here

这是通过制作一层 geom_text 在中间获得 x 轴标签的方法。并将其放置在顶部刻面下方的 y 范围内。我不知道一个好的“内置”方式来做到这一点。
data.frame(x = c("A", "B", "C", "D", "E"), 
a = abs(rnorm(5)),
b = abs(rnorm(5))) %>%
mutate(b = -b) %>%
gather("source", "amount", a, b) %>%
ggplot(data = .,
aes(x = x,
y = amount,
fill = source)) +
geom_col() +

# removing minor_breaks avoids grid lines in the middle space
scale_y_continuous(labels = abs, minor_breaks = NULL) +
# this creates a single copy of the text, related to one facet
geom_text(data = . %>% filter(source == "a"), aes(x, y = -.2, label = x)) +
# this allows for printing outside the plot range
coord_cartesian(clip = "off") +
facet_wrap(~source, ncol=1, scales = "free_y", shrink = TRUE ) +
theme(strip.text = element_blank(),
axis.text.x = element_blank())

enter image description here

关于r - 在ggplot中拆分y轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53199276/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com