我有一个简单的条形图,如下所示
a<-data.frame(x=c("total","male","female","low education",
"mid education","high education","working","not working"),
y=c(80,30,50,20,40,20,65,35))
a$x<-as.character(a$x)
a$x<-factor(a$x,levels=unique(a$x))
ggplot(a,aes(x,y)) +
geom_bar(stat="identity",fill="orange",width=0.4) +
coord_flip() +
theme_bw()
现在,因为x轴的水平(翻转,现在看起来像是y)彼此有关系,例如男性和女性代表性别崩溃,工作和不工作代表另一个故障等,我希望轴之间留下一些空间每次细分都是为了指出这些细分。
我已尝试使用scale_x_discrete
及其参数中断的一些内容,但似乎这不是它的方式。
有任何想法吗 ?
答案 0 :(得分:5)
我不知道在条形图中设置不同距离的方法。但是,您可以添加高度为0且组之间没有标签的栏,如下所示:
a<-data.frame(x=c("total","a","male","female","b","low education",
"mid education","high education","c","working","not working"),
y=c(80,0,30,50,0,20,40,20,0,65,35))
a$x<-factor(a$x,levels=unique(a$x))
ggplot(a,aes(x,y)) +
geom_bar(stat="identity",fill="orange",width=0.4) +
coord_flip() +
theme_bw() +
scale_x_discrete(breaks=a$x[nchar(as.character(a$x))!=1])
一些评论:
a$x
从一开始就是一个字符,因此无需在其上调用as.character
。scale_x_discrete
用于抑制标签和刻度线。结果如下:
答案 1 :(得分:2)
a<-data.frame(x=c("total","male","female","low education","mid education","high education","working","not working"),y=c(80,30,50,20,40,20,65,35))
a$x<-as.character(a$x)
a$x<-factor(a$x,levels=unique(a$x))
a$rel = c("a", "a", "a", "b", "b", "b", "c", "c") # set groups
ggplot(a, aes(rel, y, fill = factor(x))) +
geom_bar(stat = "identity", width = 0.5, position = position_dodge(0.7))
答案 2 :(得分:0)
如果要指定scale_x_discrete(或y),只需在“”和“标签”语句中出现空格的位置添加“”即可。这与第一个答案类似,但您不必为数据集添加零值。
e.g。此数据集只有8个条形,但它们分为两组,每组四个。
scale_x_discrete( 极限= C( “BMayC”, “UMayC”, “BMayN”, “UMayN”, “”, “BJuneC”, “UJuneC”, “BJuneN”, “UJuneN”), labels = c(“BMayC”,“UMayC”,“BMayN”,“UMayN”,“”,“BJuneC”,“UJuneC”,“BJuneN”,“UJuneN”))