Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Y axis won't start at 0 in ggplot

Tags:

r

ggplot2

In this plot I order the ylim to be 0, but the y axis seems to start at -1 anyway, which is very annoying. I really like the y axis to stat at 0. Solutions?

sub1=subset(table.popstat,POPSTAT==1,select=c(1,3))
ggplot(sub1, aes(x=YR,y=Freq)) + ylim(0,15) +
  geom_bar(stat='identity') + 
  annotate("text",x=3,y=14.9,label="Population status",cex=10)

Also, I have 30 plots like this, and there are many different ranges on the y axis. I need a generic code that places the text in the upper left corner of the graph no matter what the ymax is. Doable?

like image 813
Dag Avatar asked Apr 16 '16 20:04

Dag


People also ask

Why does the Y axis start below zero in ggplot2?

When creating histograms or barplots in ggplot2 we found that the data is placed at some distance from the x axis, which means the y axis starts below zero: This is because, internally, ggplot2 is expanding x and y axes by a multiplicative or additive constant 1.

Why is ggplot2 expanding x and Y axes by 1?

This is because, internally, ggplot2 is expanding x and y axes by a multiplicative or additive constant 1. This makes sense in almost all plots, except for the bar and histogram ones, as we see above.

Do the X-and Y-axes of a ggplot2 scatterplot start at zero?

Figure 1 shows the output of the previous code: A ggplot2 scatterplot with default axis ranges. As you can see, the x- and y-axes do not start at zero.

How to display 0 at y-axis in R using Ggplot2?

To display 0 at Y-axis, we can set the limits for Y-axis using scale_y_continuous function of ggplot2 package. For example, if we have two columns say x and y in an R data frame called df then the scatterplot with displaying 0 at Y-axis can be created by using the below command


1 Answers

ggplot automatically extends the axes slightly to make sure there is room for points to plot. You can turn this behaviour off with the expand argument

ggplot(sub1, aes(x=YR,y=Freq)) + 
  geom_bar(stat='identity') + 
  annotate("text",x=3,y=14.9,label="Population status",cex=10) +
  scale_y_continuous(expand = c(0, 0), limits = c(0, 15))
like image 53
Richard Telford Avatar answered Oct 19 '22 03:10

Richard Telford