facet-style titles in non-facetted plots

Viewed 874

I like very much the style of the titles of facet plots:

require(ggplot2)
df <- data.frame(x = rnorm(1E3), labels = as.factor(c(rep("plot1",500), rep("plot2",500))));
ggplot(df, aes(x=x) ) + geom_histogram() +facet_wrap(~labels)

facets

And I would like to format other plots' titles in a similar fashion. When I just add ggtitle() to the plot, I get the following:

ggplot(df, aes(x=x) ) + geom_histogram() +ggtitle('plot1 and plot2')

ggtitle

How can I format the ggtitle title to look like the facet_wrap title?

Thank you!

2 Answers

aosmith's example is good but sometimes you might need to plot multiple data sets at once. In cases like that, it's better to create a dummy data set containing only the title and use it in facet_wrap. Here is an example;

require(ggplot2)
df <- data.frame(x = rnorm(1E3), 
                 labels = as.factor(c(rep("plot1",500), 
                                      rep("plot2",500))))
head(df)

            x labels
1 -1.23282556  plot1
2  1.00436360  plot1
3 -0.35275785  plot1
4  0.78827732  plot1
5  0.05207618  plot1
6 -1.75324781  plot1

You can then plot the data:

ggplot(data = data.frame(ftitle = "Plot1 and Plot2")) + 
  facet_wrap(~ ftitle) +
  geom_histogram(data = df,
                 aes(x = x))

enter image description here

I needed to do it this way today, I hope somebody else might find it useful.

Related