Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rescaling the y axis in bar plot causes bars to disappear : R ggplot2

Tags:

r

ggplot2

I am trying to create a barplot using ggplot2, with the y axis starting at a value greater than zero.

Lets say I have the means and standard errors for hypothetical dataset about carrot length at three different farms:

carrots<-NULL carrots$Mean<-c(270,250,240) carrots$SE<-c(3,4,5) carrots$Farm<-c("Plains","Hill","Valley") carrots<-data.frame(carrots) 

I create a basic plot:

p<-ggplot(carrots,aes(y=Mean,x=Farm)) +    geom_bar(fill="slateblue") +    geom_errorbar(aes(ymin=Mean-SE,ymax=Mean+SE), width=0) p 

This is nice, but as the scale runs from 0 to it is difficult to see the differences in length. Therefore, I would like to rescale the y axis to something like c(200,300). However, when I try to do this with:

p+scale_y_continuous('Length (mm)', limit=c(200,300)) 

The bars disappear, although the error bars remain.

My question is: is it possible to plot a barplot with this adjusted axis using ggplot2?

Thank you for any help or suggestions you can offer.

like image 471
susjoh Avatar asked May 09 '11 11:05

susjoh


People also ask

What are error bars in GGPlot2?

Data Visualization using GGPlot2. Error Bars are used to visualize the variability of the plotted data. Error Bars can be applied to graphs such as, Dot Plots, Barplots or Line Graphs, to provide an additional layer of detail on the presented data.

How do I change the Y-axis scale in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

What does Geom_bar do in R?

geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead.


Video Answer


1 Answers

Try this

p + coord_cartesian(ylim=c(200,300)) 

Setting the limits on the coordinate system performs a visual zoom; the data is unchanged, and we just view a small portion of the original plot.

barplot example

like image 54
rcs Avatar answered Sep 19 '22 01:09

rcs