使用ggplot2调整条形图高度

3
df2 <- iris[c(5,1)]
df3 <- aggregate(df2$Sepal.Length, list(df2$Species), mean)
names(df3) <- c("x","y")

ggplot(df3, aes(x,y)) +
  geom_bar(aes(fill=x),stat="identity") +
  theme(axis.ticks=element_blank(), axis.text.x=element_blank())

enter image description here

我已成功地从这个图表中移除了轴刻度线和标签。我正在尝试去掉柱形图下方的空白灰色空间。零应该是图表的下限。我一直在搜索一个调整函数,要么将柱形图向下拉,要么截断底部的灰色部分。希望ggplots没有硬编码额外的空间。

2
看看这篇帖子,解决方案可能适用于你。(你可能只需要print(p + scale_y_continuous(expand = c(0, 0)))) - NicE
1个回答

2

根据这个问题与回答的启示,将以下元素添加到您的代码中:

theme_classic()
scale_x_discrete(expand=c(0,0))
scale_y_continuous(expand=c(0,0))

除了使用theme_classic()之外,您还可以使用theme_bw(),它将在绘图中添加水平和垂直线。

您的代码应该如下所示:

ggplot(df3, aes(x,y)) +
  geom_bar(aes(fill=x),stat="identity") +
  scale_x_discrete(expand=c(0,0)) +
  scale_y_continuous(expand=c(0,0)) +
  theme_classic() +
  theme(axis.ticks=element_blank(), axis.text.x=element_blank())

这将会给出:

在此输入图片描述


有没有办法将左边的图例与轴分开?我将 scale_x_discrete(expand=c(0,0)) 更改为 scale_x_discrete(expand=c(0.1,0)),它确实起作用了,但我不确定这是否是最好的方法。 - Pablo Herreros Cantis
1
@PabloHerrerosCantis 你也可以通过将 geom_barwidth 参数设置为小于 0.9 的值来实现。 - Jaap

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接