【问题标题】:How do you reduce the xaxis size on a line graph for a categorical x-variable using ggplot in R?如何使用 R 中的 ggplot 减小分类 x 变量的折线图上的 x 轴大小?
【发布时间】:2021-08-23 23:41:52
【问题描述】:

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

#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

图表的左右空白太多,我想“放大”或限制x轴限制,但我不知道该怎么做,因为它是一个分类x变量.有谁知道怎么做?

谢谢!

【问题讨论】:

    标签: r ggplot2 categorical-data linegraph


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-11
      • 2014-01-01
      • 2022-12-01
      相关资源
      最近更新 更多