user2726449
user2726449

Reputation: 627

xlim not working for discrete values [ggplot2]

I'm trying to set xlim and ylim in ggplot put using the below:

ylim=c(0, 1.5) +
xlim=c(0,100) +

OR

coord_cartesian(xlim = c(0, 100), ylim = (0,1.5)) +

Seems to throw this error:

Error in scale_x_discrete(breaks = c(0, 50, 100), labels = c(0,  : 
  non-numeric argument to binary operator

Is this because I'm using a discrete scale for x? I am using a numeric for y.

Using

scale_y_continuous(limits = c(0, 1.5)) +

seems to work but gives the error:

Warning message:
Removed 2 rows containing missing values (geom_path). 

Any suggestions on what I can try?

Full code:

cfr <- ggplot(sn, aes(x = mmad,y = fr, group=Plan, colour = Plan)) +
                  geom_line(size=0.5) +
                  #scale_y_continuous(limits = c(0, 1.5)) +
                  scale_x_discrete(breaks = c(0,50,100), labels= c(0,50,100)) +
                  labs(x = "mmad",y = "%")

P.S.

Without putting the axis limits in, the above code worked without a problem

Upvotes: 5

Views: 11208

Answers (1)

Daniel
Daniel

Reputation: 7832

I'm not sure, but I guess that discrete scales only accept characters as limit-parameters, each character representing a factor level (see http://docs.ggplot2.org/0.9.3.1/discrete_scale.html).

df <- data.frame(x=sample(1:3, 10, replace=TRUE), y=sample(20:30, 10, replace=TRUE))
df$x <- as.factor(df$x)
cfr <- ggplot(df, aes(x = x,y = y)) +
  geom_line(size=0.5) +
  scale_x_discrete(breaks = c(0,50,100), labels= c(0,50,100), limits=c("1", "2", "3")) +
  labs(x = "mmad",y = "%")

Works for me... (see limits parameter in scale_x_discrete).

Upvotes: 5

Related Questions