[英]How to increase the space between the bars in a bar plot in 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()
與width
的以下其他設置進行比較:
到現在為止還挺好。 現在,假設我們有兩個因素。 如果您想要使用均勻間隔的並置條(如在barplot()
使用space
和beside=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 $ -axis的向量在data.frame中“注入”,因此您可以根據需要更改外部間距,而width
允許控制內部間距。 可以使用scale_x_discrete()
增強$ x $ scale_x_discrete()
。
對於因子欄之間的空間使用
ggplot(data = d, aes(x=X, y=Y, fill=F))
+ geom_bar(width = 0.8, position = position_dodge(width = 0.9))
geom_bar中的寬度控制相對於x軸的條寬度,而position_dodge中的寬度控制兩個條形相對於x軸的寬度。 玩寬度找到你喜歡的寬度。
非常感謝你。 我有同樣的問題,你幫我解決了。 我使用scale_x_continuous而不是使用geom_text添加X標簽(見下文)
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)
取而代之
scale_x_continuous(breaks=c(mean(x.seq[1:2]), mean(x.seq[3:4])), labels=c("X", "Y"))
對於POSIXlt條之間的空間,您需要根據一天中的秒數調整寬度
# POSIXlt example: full & half width
d <- data.frame(dates = strptime(paste(2016, "01", 1:10, sep = "-"), "%Y-%m-%d"),
values = 1:10)
ggplot(d, aes(dates, values)) +
geom_bar(stat = "identity", width = 60*60*24)
ggplot(d, aes(dates, values)) +
geom_bar(stat = "identity", width = 60*60*24*0.5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.