在ggplot2中在条之间添加空间

时间:2023-02-09 16:32:45

Dear all, I'd like to add spaces between bars in ggplot2. This page offers one solution: http://www.streamreader.org/stats/questions/6204/how-to-increase-the-space-between-the-bars-in-a-bar-plot-in-ggplot2. Instead of using factor levels for the x-axis groupings, however, this solution creates a numeric sequence, x.seq, to manually place the bars and then scales them using the width() argument. width() doesn't work, however, when I use factor level groupings for the x-axis as in the example, below.

亲爱的大家,我想在ggplot2中的条之间添加空格。这个页面提供了一个解决方案:http://www.streamreader.org/stats/questions/6204/how-to-increase-the- bar- in-ggplot2。然而,这个解决方案没有使用x轴分组的因子级别,而是创建一个数字序列x。seq,手工放置这些条,然后使用width()参数对它们进行缩放。然而,当我为x轴使用因子级分组时,width()不起作用,如下面的示例所示。

library(ggplot2)

Treatment <- rep(c('T','C'),each=2)
Gender <- rep(c('M','F'),2)
Response <- sample(1:100,4)
df <- data.frame(Treatment, Gender, Response)

hist <- ggplot(df, aes(x=Gender, y=Response, fill=Treatment, stat="identity"))
hist + geom_bar(position = "dodge") + scale_y_continuous(limits = c(0, 
    100), name = "") 

Does anyone know how to get the same effect as in the linked example, but while using factor level groupings?

是否有人知道如何获得与链接示例相同的效果,但在使用因子水平分组时?

Cheers,

欢呼,

Aaron

亚伦

1 个解决方案

#1


67  

Is this what you want?

这是你想要的吗?

hist + geom_bar(width=0.4, position = position_dodge(width=0.5))
  • width in geom_bar determines the width of the bar.
  • geom_bar中的宽度决定了bar的宽度。
  • width in position_dodge determines the position of each bar.
  • position_dodge中的宽度确定每个bar的位置。

Probably you can easily understand their behavior after you play with them for a while.

也许你可以在和他们玩一段时间后很容易地理解他们的行为。

在ggplot2中在条之间添加空间

#1


67  

Is this what you want?

这是你想要的吗?

hist + geom_bar(width=0.4, position = position_dodge(width=0.5))
  • width in geom_bar determines the width of the bar.
  • geom_bar中的宽度决定了bar的宽度。
  • width in position_dodge determines the position of each bar.
  • position_dodge中的宽度确定每个bar的位置。

Probably you can easily understand their behavior after you play with them for a while.

也许你可以在和他们玩一段时间后很容易地理解他们的行为。

在ggplot2中在条之间添加空间