如何使用 R 中的 ggplot2 将 Y 轴标题更改为水平?

在 R 中使用 ggplot2 的 Y 轴标题的默认方向是垂直的,我们可以更改为水平。为此,我们可以使用 ggplot2 包的主题功能。我们需要将主题函数的参数用作axis.title.y=element_text(angle=0)),这会将Y轴标题写入水平,但位置将更改为顶部。

示例

考虑以下数据框 -

x<−rnorm(100)
df<−data.frame(x)
head(df,20)
输出结果
x
1 −0.5417569
2 −0.4018531
3 0.2178570
4 1.1911282
5 0.5977775
6 0.5790850
7 −0.5143645
8 0.5056482
9 1.1791990
10 −0.2668907
11 −0.4142607
12 −0.3763989
13 0.6037290
14 −0.4162111
15 −0.1434954
16 1.9538955
17 0.2724839
18 1.7957378
19 1.9833760
20 −0.9305919

加载 ggplot2 包并创建 x 的直方图 -

示例

library(ggplot2)
ggplot(df,aes(x))+geom_histogram(bins=30)
输出结果

将 Y 轴标题方向更改为水平 -

示例

ggplot(df,aes(x))+geom_histogram(bins=30)+theme(axis.title.y=element_text(angle=0))
输出结果