如何使用 ggplot2 增加条形图中轴线和条形之间的间距

How to increase space between axis line and bars in a bar plot using ggplot2

提问人:goshawk 提问时间:11/1/2023 最后编辑:MrFlickgoshawk 更新时间:11/1/2023 访问量:28

问:

如何增加 y 轴线与以下条形图中第一个条形之间的间距?

# Load ggplot
library(ggplot2)

# Load the Titanic dataset
data("Titanic")
Titanic <- as.data.frame(Titanic)

# Bar plot
ggplot(Titanic, aes(x = Class, y = Freq, fill = Survived)) + 
  geom_col(position = "fill") +
  coord_cartesian(ylim = c(0, 1), expand = FALSE) +
  theme_classic() +
  theme(legend.position = "none",
        axis.line.x = element_blank(),
        axis.ticks.x = element_blank())

有没有办法只应用于 x 轴?这可以解决问题。coord_cartesian(expand = FALSE)

enter image description here

R ggPlot2 条形图 间距

评论

0赞 camille 11/1/2023
很确定这是 stackoverflow.com/q/22945651/5325862 的骗局

答:

1赞 MrFlick 11/1/2023 #1

我不认为你可以用 .您可以改用刻度coord_cartesion

ggplot(Titanic, aes(x = Class, y = Freq, fill = Survived)) + 
  geom_col(position = "fill") +
  scale_x_discrete(expand=expansion(add=c(.8, 0))) + 
  scale_y_continuous(expand=expansion(add=c(0, 0))) + 
  theme_classic() +
  theme(legend.position = "none",
        axis.line.x = element_blank(),
        axis.ticks.x = element_blank())

将 .8 的值更改为您喜欢的任何值。

enter image description here