如何使用 R 中的 ggplot 减小分类 x 变量的折线图上的 x 轴大小?

How do you reduce the xaxis size on a line graph for a categorical x-variable using ggplot in R?

我正在使用 ggplot 中的折线图使用以下代码绘制男性和女性干预前和 post 之间的体重变化:

#Load Packages
library(tidyverse)
library(ggplot2)
library(dplyr)
library(gapminder)
library(magrittr)

#Create dataframe
Wt_2 <- data.frame(ID = c(1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8), Sex = c("Male", "Male", "Male", "Male", "Female", "Female","Female","Female"), 
                   Weight_Lbs = c(252.8,181.7,294.9,220.5,204.9,209.1,252.5,179.5,237.0,
                                  169.0,277.0,215.0,200.0,204.0,242.9,172.0),
                   Timepoint = c("Pre","Pre","Pre","Pre",
                                 "Pre","Pre","Pre","Pre",
                                 "Post","Post","Post","Post",
                                 "Post","Post","Post","Post"))
#Convert to KG
Wt_2$Weight_Kg <- Wt_2$Weight_Lbs*0.45359237

#Make factors
Wt_2$ID_f <- factor(Wt_2$ID)
Wt_2$Sex <- factor(Wt_2$Sex)
Wt_2$Timepoint <- factor(Wt_2$Timepoint, levels = c("Pre","Post"))
Wt_2$Timepoint

as_tibble(Wt_2)

#Graph
ggplot(data = Wt_2, aes(x = Timepoint, y = Weight_Kg, group = ID_f)) + 
  geom_line(aes(color = Sex)) + xlab("Time") + ylab("Weight (Kg)") +
  geom_point(aes(color = Sex, shape = Sex)) +
  scale_color_manual(values=c("#E69F00","darkorchid1")) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

图表如下所示: Line Graph

图表左右空白太多space,想“放大”或限制x轴的限制,但不知如何操作,因为它是一个分类 x 变量。有人知道怎么做吗?

谢谢!

x 轴默认有一些填充,您可以使用 scale_x_discrete(expand = c(0.1, 0.1))

进行调整
ggplot(data = Wt_2, aes(x = Timepoint, y = Weight_Kg, group = ID_f)) + 
  geom_line(aes(color = Sex)) + xlab("Time") + ylab("Weight (Kg)") +
  geom_point(aes(color = Sex, shape = Sex)) +
  scale_x_discrete(expand = c(0.1, 0.1)) +
  scale_color_manual(values=c("#E69F00","darkorchid1")) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())