简体   繁体   中英

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

I'm graphing change in weight between pre and post intervention for males and females using a line graph in ggplot using the following code:

#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())

This is what the graph looks like: Line Graph

There is too much blank space on the left and right of the graph, I'd like to "zoom in" or restrict the xaxis limit, but I don't know how to do this since it is a categorical x variable. Does anyone know how to do this?

Thanks!

The x-axis default has some padding around them, which you can adjust with 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())

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM