ggplot2 - x axis limits for ggplot bar graph in R -


how can set limits on x axis ggplot graph? 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 array 6:16. grouping variable sex, there 2 bars each age (different colors). mean variable of interest, vertical line se.

i used scale_x_discrete(breaks=ages) since wanted ages 6 16 displayed.

in function xlim() commented since creates conflict scale_x_discete()

now resulting graph has x axis 0 16, want make start 6, avoiding show empty part of graph ages 0 6 in image linked below.

can solve this?

enter image description here

use scale_x_continuous rather scale_x_discrete.

df_gp  + scale_x_continuous(breaks=ages) 

enter image description here

if want zoom x labels can add limits parameter:

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

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -