gpt4 book ai didi

r - 如何增加ggplot2条形图中条形之间的间距?

转载 作者:行者123 更新时间:2023-12-03 05:53:58 28 4
gpt4 key购买 nike

如何增加ggplot2中条形图中条形之间的间距?

最佳答案

您始终可以使用width参数,如下所示:

df <- data.frame(x=factor(LETTERS[1:4]), y=sample(1:100, 4))
library(ggplot2)
ggplot(data=df, aes(x=x, y=y, width=.5)) +
geom_bar(stat="identity", position="identity") +
opts(title="width = .5") + labs(x="", y="") +
theme_bw()

与以下其他宽度设置进行比较:

alt text

到目前为止,一切都很好。现在,假设我们有两个因素。如果您想使用均匀间隔的并置条形(例如在 barplot() 中将 spacebeside=TRUE 一起使用时),可以使用使用 geom_bar(position="dodge") 不太容易:您可以更改条形宽度,但不能在相邻条形之间添加空间(我在 Google 上没有找到方便的解决方案)。我最终得到了类似的结果:

df <- data.frame(g=gl(2, 1, labels=letters[1:2]), y=sample(1:100, 4))
x.seq <- c(1,2,4,5)
ggplot(data=transform(df, x=x.seq), aes(x=x, y=y, width=.85)) +
geom_bar(stat="identity", aes(fill=g)) + labs(x="", y="") +
scale_x_discrete(breaks = NA) +
geom_text(aes(x=c(sum(x.seq[1:2])/2, sum(x.seq[3:4])/2), y=0,
label=c("X","Y")), vjust=1.2, size=8)

用于 $x$ 轴的向量被“注入(inject)”到 data.frame 中,因此您可以根据需要更改外部间距,而 width 允许控制内部间距。 $x$ 轴的标签可以通过使用 scale_x_discrete() 来增强。

alt text

关于r - 如何增加ggplot2条形图中条形之间的间距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12040245/

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