你好,这个简单的代码(以及我今天早上的所有脚本)在ggplot2中开始给我一个偏离中心的标题
Ubuntu version: 16.04
R studio version: Version 0.99.896
R version: 3.3.2
GGPLOT2 version: 2.2.0
我今天早上重新安装了上述软件,试图解决这个问题....。
dat <- data.frame(
time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23)
)
# Add title, narrower bars, fill color, and change axis labels
ggplot(data=dat, aes(x=time, y=total_bill, fill=time)) +
geom_bar(colour="black", fill="#DD8888", width=.8, stat="identity") +
guides(fill=FALSE) +
xlab("Time of day") + ylab("Total bill") +
ggtitle("Average bill for 2 people")
来自ggplot 2.2.0
的发布新闻。"主情节标题现在是左对齐的,以便更好地与副标题配合使用"。参见?theme
中的plot.title
参数:"默认为左对齐"。
正如@J_F所指出的,你可以添加theme(plot.title = element_text(hjust = 0.5))
来将标题居中。
ggplot() +
ggtitle("Default in 2.2.0 is left-aligned")
ggplot() +
ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
theme(plot.title = element_text(hjust = 0.5))
正如Henrik的回答中所述,从ggplot 2.2.0开始,标题默认是左对齐的。标题可以通过在绘图中添加这个来居中。
theme(plot.title = element_text(hjust = 0.5))
然而,如果你创建了很多图,在所有地方添加这行字可能会很繁琐。然后,我们还可以用以下方法改变ggplot的默认行为
theme_update(plot.title = element_text(hjust = 0.5))
一旦你运行了这一行,之后创建的所有图都将使用主题设置plot.title = element_text(hjust = 0.5)
作为其默认值。
theme_update(plot.title = element_text(hjust = 0.5))
ggplot() + ggtitle("Default is now set to centered")
要恢复到原来的ggplot2默认设置,你可以重新启动R会话,或者用以下方法选择默认主题
theme_set(theme_gray())