R中ggplot条形图的x轴限制 [英] x axis limits for ggplot bar graph in R

查看:388
本文介绍了R中ggplot条形图的x轴限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为ggplot图设置x轴上的限制?我的代码是

How can I set limits on the x axis for a ggplot graph? My code is

    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

ages是一个6:16的数组.分组变量是性别,因此每个年龄段都有两个条形(不同的颜色).平均值是关注变量,垂直线是se.

ages is an array 6:16. grouping variable is sex, so there are two bars for each age (different colors). mean is the variable of interest, the vertical line is the se.

我使用了scale_x_discrete(breaks = ages),因为我希望显示6到16岁之间的所有年龄段.

I used scale_x_discrete(breaks=ages) since I wanted all the ages from 6 to 16 to be displayed.

被注释,因为它与scale_x_discete()产生了冲突

in the function xlim() is commented since it creates a conflict with scale_x_discete()

现在生成的图的x轴从0到16,我要使其从6开始,这样就避免了显示0到6岁之间图的空白部分,如下图所示.

Now the resulting graph has x axis from 0 to 16, I want to make it start from 6, thus avoiding to show the empty part of the graph from ages 0 to 6 as in the image linked below.

我能解决这个问题吗?

推荐答案

使用scale_x_continuous而不是scale_x_discrete.

df_GP  + scale_x_continuous(breaks=ages)

如果要缩放x标签,可以添加limits参数:

If you want to zoom the x labels you can add limits parameter:

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

这篇关于R中ggplot条形图的x轴限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆