Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

r - Set y limits in Bar Chart ggplot2

I have created a bar chart which shows the sales of products in a particular category. This is the bar chart. As you can see it is not very clear so I am trying to set limits for the Y axis.

I create the bar chart with the following line:

bakerySales <- ggplot(sales_bakery, aes(ProductName, ProductSales))+ 
stat_summary(fun.y=sum,geom="bar",colour="red",fill="red",show.legend = 
FALSE)

I then go on to apply a theme to the bar chart using:

bakerySales <- bakerySales +
theme(axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.x = element_text(colour = "black", size = 14, angle = 60, 
    hjust = 1),
    axis.text.y = element_text(colour = "black", size = 14),
    panel.background = element_rect(fill = "white"),
    panel.grid.minor = element_blank(),
    panel.grid.major = element_blank(),
    axis.line = element_line(colour = "black", size = 1),
    legend.position = "none",
    plot.title = element_text(lineheight = 8, face = "bold"))

I have tried to set the limits for the y axis using:

bakerySales <- bakerySales + ylim(5000,10000)

When I do this I lose the content of the bar chart, It looks like this.

Can someone please tell me where I am going wrong.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to zoom in on specifix ylimits, you could use the coord_cartesian function. I do not have the bakerysales dataset, this is an example using mtcars data:

ggplot(mtcars, aes(x = gear, y = qsec)) +
  stat_summary(fun.y=sum,geom="bar",colour="red",fill="red",show.legend = FALSE) +
  coord_cartesian(ylim = c(200, 300))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...