Seth W. Bigelow
Seth W. Bigelow

Reputation: 61

Expand colored part of area plot in ggplot

I wish to expand the colored part of an area plot in ggplot so that there is not so much grey space at the ends of the X axis. When I use scale_x_discrete(limits...), the colored part of the graph automatically shrinks, defeating the purpose. Here's an example

df1 <- data.frame(sex       = factor(c("Female","Female","Male","Male")),
             time       = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
             total_bill = c(13.53, 16.81, 16.24, 17.42))

library(ggplot2)
ggplot(data=df1, aes(x=rep(c(1,2),2), y=total_bill, fill=sex)) + 
geom_area() +
scale_x_discrete(labels=df1$time)

Too much grey space, not enough colored graph

ggplot(data=df1, aes(x=rep(c(1,2),2), y=total_bill, fill=sex)) +
geom_area() +
scale_x_discrete(limits=c(0.8,2.2), labels=df1$time)

X axis ticks are nearer the edge of the figure, but now the colored part has shrunken and gray space remains the same.

Upvotes: 1

Views: 837

Answers (2)

JeremyS
JeremyS

Reputation: 3525

You can also use coord_cartesian, which is very useful for a lot of different plots, it changes the zoom without affecting where the actual data is plotted.

ggplot(data=df1, aes(x=rep(c(1,2),2), y=total_bill, fill=sex)) + 
  geom_area() +
  scale_x_discrete(labels=df1$time) +
  coord_cartesian(xlim=c(0.8,2.2))

Upvotes: 0

David Arenburg
David Arenburg

Reputation: 92302

use expand in scale_x_discrete

as if

library(ggplot2)
ggplot(data=df1, aes(x=rep(c(1,2),2), y=total_bill, fill=sex)) + 
  geom_area() +
  scale_x_discrete(labels=df1$time, expand=c(0.2, 0))

enter image description here

Upvotes: 3

Related Questions