如何在 R 中使用 ggplot2 将情节标题放在情节中?

通常,我们将情节标题放在情节的顶部,但我们也可以将其放在情节内。当然,这会改变图表的显示方式,但也会吸引观众。为此,我们可以使用 ggplot2 包的主题功能,其中绘图标题的边距参数将改变标题的位置。

考虑以下数据框 -

示例

x<-rnorm(20)
y<-rnorm(20)
df<-data.frame(x,y)
df
输出结果
       x           y
1  -0.30662899  -0.37957405
2  -0.82615057  -1.26477881
3  -0.11692952   0.01427444
4  -0.34331938   2.03706444
5  -1.49544241   0.35632086
6  -0.07656434  -1.68049294
7  -0.05300648  -0.24720322
8   1.24363223   0.84503405
9  -0.05653599  -1.18044286
10 -0.04502879   0.43735809
11  0.04637793   0.47158401
12 -0.52382139  -1.02630948
13  1.60555319   0.64673159
14  1.80033105  -1.79870479
15 -0.10558775  -0.02166056
16 -0.68224275   0.61533007
17 -1.79128676  -0.45239927
18  0.34083402  -0.95344404
19 -0.39968860  -0.20690004
20 -0.53267410   2.17089520

加载 ggplot2 包并在 x 和 y 之间创建散点图 -

示例

library(ggplot2)
ggplot(df,aes(x,y))+geom_point()+ggtitle("Scatterplot")
输出结果

在绘图区域内使用绘图标题创建 x 和 y 之间的散点图 -

示例

ggplot(df,aes(x,y))+geom_point()+ggtitle("Scatterplot")+theme(plot.title=element_text(margin=margin(t=10,b=-20)))
输出结果