Rick
Rick

Reputation: 11

Why is the ylim() function in ggplot2 being ignored?

I want the y axis in a line chart to show a wider range of values because the upper and lower data points are well away from the default maximum and minimum values shown on the axis – I want to set the limits to -0.07 and 0.07. However, the code to set the y axis seems to be ignored – here is my code:

scale<-c("250 m", "500 m", "1 km", "2 km", "3 km", "4 km", "5 km")
scales<-factor(scale, levels=c("250 m", "500 m", "1 km", "2 km", "3 km", "4 km", "5 km"))

coefs<-c(-0.069, -0.023, -0.006, 0.041, 0.069, 0.066, 0.07)
coef.scales=data.frame(scales,coefs)

coef.fig<-ggplot(data = coef.scales, aes(scales, coefs, group = 1))+
  geom_point() +
  geom_line() +
  labs(x = "Scale", y = "Standardized coefficient") + 
  theme_classic(base_size = 17) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  ylim(-0.07, 0.07)

As well as the ylim(-0.07, 0.07) command I’ve also tried scale_y_continuous(-0.07, 0.07) and coord_cartesian(ylim = c(-0.07, 0.07)). The default figure remains unchanged, with 3 values on the y scale ranging from -0.04, 0.04. Why can’t I change the values shown on the y axis?

Upvotes: 1

Views: 2156

Answers (1)

user10917479
user10917479

Reputation:

I think you are trying to set the breaks. Your code does in fact set the y limits. It just does not label them as you are expecting.

coef.fig<-ggplot(data = coef.scales, aes(scales, coefs, group = 1))+
  geom_point() +
  geom_line() +
  labs(x = "Scale", y = "Standardized coefficient") + 
  theme_classic(base_size = 17) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  scale_y_continuous(limits = c(-0.07, 0.07), breaks = c(-0.07, 0, 0.07))

enter image description here

Upvotes: 1

Related Questions