Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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.

like image 449
Tom Avatar asked Dec 05 '25 05:12

Tom


1 Answers

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))
like image 91
Koundy Avatar answered Dec 07 '25 20:12

Koundy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!