簡體   English   中英

R中ggplot條形圖的x軸限制

[英]x axis limits for ggplot bar graph in R

如何為ggplot圖設置x軸限制? 我的代碼是

    ages <- 6:16
    mu <-  c(0.66849315, 0.55386301,  1.17609589, 0.26111781,  0.46629253,  0.87089041, 0.62037671, 0.26995434, -0.30502283, -0.54611872, NaN, NaN, -0.69132420, 1.09863014,  0.49794521,  0.12393655,  0.05128425,  0.28188737, 0.41315068, 0.15585997, 0.54246575, 0.23561644)
    ss <- c(NA, NA, 0.4621444, 0.1906852, 0.2239675, 0.1860610, 0.2789741, 0.2251610, 0.6729181, 0.2931649, NA, NA, 0.3996913, 0.8912500, 0.3567265, 0.2089201, 0.2070513, 0.2167448, 0.2518419 ,0.2484582, NA, NA)
    df_GP <- data.frame( 
       age = c(ages, ages),
       group = c(rep("F", length(ages)), rep("M", length(ages))),
       mean = mu,   
       se = ss
    )
    limits <- aes(ymax = mean + se, ymin=mean - se)
    dodge <- position_dodge(width=0.9)
    p_GP <- ggplot(df_GP, aes(fill=group, y=mean, x=age)) + 
        geom_bar(position="dodge", stat="identity") + 
        geom_errorbar(limits, position=dodge, width=0) + 
        ylim(-4, 2.5) +
        ggtitle("GP") +
        scale_x_discrete(breaks=ages) +
        #xlim(5, 17) +
        theme(legend.position="none") 
     p_GP

年齡是陣列6:16。 分組變量是性別,因此每個年齡(不同顏色)有兩個條形。 mean是感興趣的變量,垂直線是se。

我使用了scale_x_discrete(breaks = ages),因為我希望顯示從6到16的所有年齡。

在函數xlim()中注釋,因為它與scale_x_discete()產生沖突

現在生成的圖形的x軸從0到16,我想讓它從6開始,從而避免顯示從0到6歲的圖形的空白部分,如下面鏈接的圖像。

我能解決這個問題嗎?

在此輸入圖像描述

使用scale_x_continuous而不是scale_x_discrete

df_GP  + scale_x_continuous(breaks=ages)

在此輸入圖像描述

如果要縮放x標簽,可以添加limits參數:

 scale_x_continuous(breaks=ages,limits=c(10, 17)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM