R ggplot2减少钢筋宽度和钢筋间距 [英] R ggplot2 reducing bar width and spacing between bars
问题描述
我一直在阅读帖子并寻找我的问题的答案,但无法找到答案。这是基本的想法。我使用ggplot生成堆叠条形图,其中每个条形按组分解,并且图形在水平轴上翻转。我知道如何使用宽度选项来更改条的宽度,但减小条宽会在条之间留下大量空白区域。问题:如何去除条形图之间的大量空间?
I've been reading posts and searching for an answer to my problem but can't find one. Here's the basic idea. I'm using ggplot to produce a stacked barchart where each bar is broken down by group and the plot is flipped on the horizontal axis. I know how to change the width of the bars using the "width" option, however reducing the bar width leaves a lot of white space between the bars. Question: how do I remove the huge amounts of space between the bars?
我使用前面的问题拼凑了一些可重现的代码,答案是根据我的需要量身定制的。
I've cobbled together some reproducible code using a previous question & answer that has been tailored to my needs. Any help would be appreciated!
df <- structure(list(A = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L,
3L), .Label = c("0-50,000", "50,001-250,000", "250,001-Over"), class = "factor"),
B = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("0-50,000",
"50,001-250,000", "250,001-Over"), class = "factor"), Freq = c(0.507713884992987,
0.258064516129032, 0.23422159887798, 0.168539325842697, 0.525280898876405,
0.306179775280899, 0.160958904109589, 0.243150684931507,
0.595890410958904)), .Names = c("A", "B", "Freq"), class = "data.frame", row.names = c(NA,
-9L))
library(ggplot2)
bp <- ggplot(data=df, aes(x=A, y=Freq))+
geom_bar(width=0.2,stat="identity",position="fill") +
theme_bw() +
theme(axis.title.y=element_blank()) +
theme(axis.text.y=element_text(size=10)) +
theme(axis.title.x=element_blank()) +
theme(legend.text=element_text(size=10)) +
theme(legend.title=element_text(size=10)) +
scale_y_continuous(labels = percent_format())
bp + geom_bar(colour="white",width=0.2,stat="identity",position="fill",show_guide=FALSE) + coord_flip() +theme(panel.grid.minor=element_blank(), panel.grid.major=element_blank())+ theme(legend.position="bottom")
推荐答案
您可以使用 coord_equal
来改变整个绘图的宽高比,并从 geom_bar中移除
。宽度
参数
You could change the aspect ratio of the whole plot using coord_equal
and remove the width
argument from geom_bar
.
library(ggplot2)
library(scales)
ggplot(data=df, aes(x=A, y=Freq)) +
geom_bar(stat="identity",position="fill") +
theme_bw() +
theme(axis.title.y=element_blank()) +
theme(axis.text.y=element_text(size=10)) +
theme(axis.title.x=element_blank()) +
theme(legend.text=element_text(size=10)) +
theme(legend.title=element_text(size=10)) +
scale_y_continuous(labels = percent_format()) +
geom_bar(colour="white",stat="identity",position="fill",show_guide=FALSE) +
theme(panel.grid.minor=element_blank(), panel.grid.major=element_blank()) +
theme(legend.position="bottom") +
coord_equal(1/0.2) # the new command
这种方法的缺点是它不适用于 coord_flip
。
The drawback of this approach is that it does not work with coord_flip
.
这篇关于R ggplot2减少钢筋宽度和钢筋间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!