我正在尝试制作几个条形图。创建条形图时,我必须减小条形宽度、条形之间的间距以及条形和轴之间的间距。但是,我无法在 ggplot2 中得到我想要的东西。所以我切换到 R 基本条形图。但我这里也有一些问题。这是我的示例代码:
d.f=data.frame(group=c("a","b","c","d"),val=c(150,120,100,60)) #data_frame
dev.new(width=30.95625,height=16.16604,units="cm",res=300)
#plot with ggplot2
library(ggplot2)
ggplot() +
geom_bar(data = d.f,
aes(x = group,y = val, fill = group,
group = group),width=0.5,
position="dodge",
stat = "identity") +
scale_x_discrete(expand=c(-10,10.2))+
scale_y_continuous(limits=c(0,200),expand=c(0,0))+
theme_bw()+
scale_fill_manual(values=c("red","red","blue","blue"))+
theme(plot.margin=margin(0.2,0.2,0.2,0.2,"cm"),
axis.text.y=element_text(color="black",hjust=1),
axis.text.x=element_text(color="black"),
legend.position="none",
panel.grid.major=element_blank(),panel.grid.minor=element_blank(),
panel.background=element_blank(),
axis.line=element_line(colour="black"))
在这里,我无法减少 bar 和 yaxis 之间的间距。另外,条形的宽度。所以我尝试使用 R 图如下:
barplot(d.f[,2],col=c("red","red","blue","blue"),axes=TRUE,xlab="group",names.arg=c("a","b","c","d"),ylim=c(0,200),axisnames=TRUE,space=c(0.2,0.2,0.2,0.2))
现在,我怎样才能得到类似于ggplot2的y轴和x轴? 另外我怎样才能得到类似于ggplot2的条形图? 我知道有很多问题要问。因此,我们非常感谢任何帮助。谢谢你。
我刚开始使用 ggplot2,但它的用途非常广泛。 我认为您只需要对代码进行一些更改即可减少空格。
见下图:
d.f = data.frame(group = c("a", "b", "c", "d"), val = c(150, 120, 100, 60))
dev.new(width = 30.95625, height = 16.16604, units = "cm", res = 300)
library(ggplot2)
ggplot() +
geom_bar(data = d.f,
aes(x = group, y = val, fill = group, group = group),
width = 0.3, # Adjust the width parameter here
position = "dodge",
stat = "identity") +
scale_x_discrete(expand = c(-10, 10.2)) +
scale_y_continuous(limits = c(0, 200), expand = c(0, 0)) +
theme_bw() +
scale_fill_manual(values = c("red", "red", "blue", "blue")) +
theme(
plot.margin = margin(0.2, 0.2, 0.2, 0.2, "cm"),
axis.text.y = element_text(color = "black", hjust = 1),
axis.text.x = element_text(color = "black"),
legend.position = "none",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black")
)