Tom
Tom

Reputation: 33

Why can't I centre adjust my title in ggplot?

I'm using ggplot to make stacked bar graphs in R. Everything is working well, and I have the title assigned to the plot, but nothing I try will get it to centre. My code at the moment is (with some labels changed):

pddis$row <- seq_len(nrow(pddis))
pddis2 <- melt(pddis, id.vars = "row")

ggplot(pddis2, aes(x=variable, y=value, fill=row)) + 
geom_bar(stat="identity", position="fill") +
xlab("\nDis") +
ylab("Percentage\n")+
ggtitle("Distribution of PD responses)+
guides(fill=guide_legend(title="PD"))+
scale_y_continuous(labels = scales::percent)+
scale_fill_continuous(labels = c("0", "1", "2", "3", "4"))+
theme(plot.title=element_text(hjust=0.5))+
theme_classic()

I have also changed ggtitle to opts and labs(title=), and used adj=0.5 in various ways, but none of these work either. Apologies if this is obvious, but I just can't work out what I'm doing wrong. The code still runs and produces the plot with these other arguments (but not opts, but the title just isn't centre aligned.

Upvotes: 3

Views: 2645

Answers (1)

Koundy
Koundy

Reputation: 5555

theme_classic is overriding your code. try adding

theme(plot.title = element_text(hjust=0.5))

After the theme_classic command. For example,

ggplot(mtcars,aes(wt,mpg)) + geom_point() + 
labs(title = 'xyz') + 
theme_classic() +
theme(plot.title = element_text(hjust=0.5))

Upvotes: 4

Related Questions