+1 vote
in Programming Languages by (7.3k points)

The following code writes the title on the top-left side of the plot. I want title to appear in the center of the plot. How can I do this?

library(ggplot2)

x <- c(1:10)

y <-sin(x)

df <-data.frame(xvals=x, yvals=y)

p1 <- ggplot(df,aes(x,y)) +

  geom_line() +

  scale_x_continuous(limits = c(0, 10), breaks = seq(0, 10, 1), minor_breaks = seq(0, 10, 0.2)) +

  scale_y_continuous(limits = c(-1, 1), breaks = seq(-1, 1, 0.5), minor_breaks = seq(-1, 1, 0.1)) +

  geom_vline(aes(xintercept=3, color="x_3"), linetype="dashed", size=1) +

  geom_vline(aes(xintercept=5, color="x_5"), linetype="dashed", size=1) +

  scale_color_manual(values = c("x_3" = "blue", "x_5" = "red")) +

  theme(panel.grid.major = element_line(colour="grey", size=0.5), panel.grid.minor = element_line(colour="white", size=0.5), legend.title=element_blank(),

        ) +

  ggtitle("test plot")

1 Answer

0 votes
by (30.2k points)

You need to add plot.title = element_text(hjust = 0.5) to the theme() function. Also, make sure that ggtitle() comes after theme(), otherwise, the code will throw a warning/error.

Here is the modified code:

library(ggplot2)
x <- c(1:10)
y <-sin(x)
df <-data.frame(xvals=x, yvals=y)
p1 <- ggplot(df,aes(x,y)) +
  geom_line() +
  scale_x_continuous(limits = c(0, 10), breaks = seq(0, 10, 1), minor_breaks = seq(0, 10, 0.2)) +
  scale_y_continuous(limits = c(-1, 1), breaks = seq(-1, 1, 0.5), minor_breaks = seq(-1, 1, 0.1)) +
  geom_vline(aes(xintercept=3, color="x_3"), linetype="dashed", size=1) +
  geom_vline(aes(xintercept=5, color="x_5"), linetype="dashed", size=1) +
  scale_color_manual(values = c("x_3" = "blue", "x_5" = "red")) +
  theme(panel.grid.major = element_line(colour="grey", size=0.5), panel.grid.minor = element_line(colour="white", size=0.5), legend.title=element_blank(),
        plot.title = element_text(hjust = 0.5)) +
  ggtitle("test plot")

...