我有以下数据集,我使用“ggplot2”为其生成了堆积条形图。
数据-->
X1 X2 X3
1 1 10 13.53
2 1 10 16.81
3 2 10 16.24
4 2 10 17.42
5 1 10 15.20
6 1 10 29.40
7 1 10 45.30
8 1 10 14.00
9 1 10 23.50
10 2 10 12.30
ggplot2 代码 --->
ggplot(data=dat1, aes(x=X2, y=X3, fill=X1,width=0.5)) +
geom_bar(stat="identity") + coord_flip() +
theme(legend.position="bottom",legend.direction="horizontal",legend.text=element_text(size=12),
plot.margin=unit(c(0.1,1,0.25,1), "cm"),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(),axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank())+
guides(fill=guide_legend(nrow=1,byrow=TRUE)) +
scale_x_continuous(breaks = 10)+
scale_y_continuous(breaks=c(seq(0,sum(dat1$X3),50),sum(dat1$X3)),expand = c(0,0))+
labs(fill="")
我现在想使用 R 的 barplot() 函数将其转换为 R 基本图,以便我可以在其他地方使用它。我无法使用基本条形图函数生成堆叠条形图,我必须使用单列但 2 个组进行堆叠。
感谢您的帮助。
最佳答案
也许这可以帮助你
X1=c(1,1,2,2,1,1,1,1,1,2)
X2=rep(10,10)
X3=c(13.53,16.81,16.24,17.42,15.20,29.40,45.30,14.00,23.50,12.30)
my.color<-rev(c("#4292C6","#08306B"))
# this is the important thing, to pass your data into barplot as a matrix
dat1<-as.matrix(X3,X2)
barplot(dat1,col = my.color[as.factor(X1)],border = my.color[as.factor(X1)],
beside = FALSE,horiz=TRUE,
xaxt="n",yaxt="n",xlab="",ylab="",main="")
axis(1, at=seq(0,sum(X3),by=50))
axis(2, at=0.7,labels = 10)
legend(0,1.4, fill=my.color, legend=c(1, 2))
结果如下:
为了将图例添加到绘图之外,您可能必须将 par() 中的 xpd 选项从 FALSE 更改为 TRUE:
par(xpd=TRUE)
希望有帮助。
关于R 基本图中的 R ggplot2 bar 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43892497/