开发者

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

开发者 https://www.devze.com 2023-03-04 10:11 出处:网络
This question already has answers here: geom_bar bars not displaying when specifying ylim (4 answers) Closed 9 months ago.
This question already has answers here: geom_bar bars not displaying when specifying ylim (4 answers) Closed 9 months ago.

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 an开发者_运维百科d 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.


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.

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


If someone is trying to accomplish the same zoom effect for a flipped bar chart, the accepted answer won't work (even though the answer is perfect for the example in the question).

The solution for the flipped bar chart is using the argument ylim of the coord_flip function. I decided to post this answer because my bars were also "disappearing" as in the original question while I was trying to re-scale with other methods, but in my case the chart was a flipped one. This may probably help other people with the same issue.

This is the adapted code, based on the example of the question:

ggplot(carrots,aes(y=Mean,x=Farm)) +
  geom_col(fill="slateblue") +
  geom_errorbar(aes(ymin=Mean-SE,ymax=Mean+SE), width=0) +
  coord_flip(ylim=c(200,300)) 

Flipped chart example

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号