对于ggplot2图,hjust和vjust是相对于整个图定义的对齐函数。因此,当它们应用于轴标签时,它们不是相对于轴线定义的。
但是,相对于轴线调整轴标题更为自然。
具体来说,我正在寻找一种左对齐x轴标题以及上对齐和旋转y轴标题的方法。
怎样才能做到这一点呢?
正如问题中所指定的,hjust并且vjust是相对于整个图定义的对齐函数。
因此,不会实现相对于轴线hjust=0起点的完美左对齐。但是,它可以与和x结合使用。expand_limitsscale_x_continuous
与轴scale_y_continuous标题类似y。
在问题的附图中,情节从原点开始。因此,首先,我们必须强制情节实际上从原点开始:
\n... +\n expand_limits(x = 0, y = 0) +\n scale_x_continuous(expand = c(0, 0)) + \n scale_y_continuous(expand = c(0, 0))\nRun Code Online (Sandbox Code Playgroud)\n然后我们可以指定调整\xe2\x80\x94,这里还添加了y轴标题的旋转,这要求我们使用hjust而不是vjust:
... +\ntheme(\n axis.title.x = element_text(hjust = 0),\n axis.title.x = element_text(angle = 90, hjust = 1)\n)\nRun Code Online (Sandbox Code Playgroud)\n首先,我们加载ggplot2并创建一个数据集:
library(ggplot2) \n\ndf <- data.frame(\n x = c(0, 50, 100),\n y = c(20, 40, 80)\n)\nRun Code Online (Sandbox Code Playgroud)\n我们创建绘图并添加一个geom_line().
graph <- \n ggplot(data=df, mapping = aes(x=x, y=y)) +\n geom_line()\nRun Code Online (Sandbox Code Playgroud)\n我们修复我们的轴。作为更好地控制轴的额外好处,我还定义了轴范围 ( limits)。
graph <-\n graph +\n scale_x_continuous(expand = c(0,0), limits = c(min(df$x), max(df$x))) +\n scale_y_continuous(expand = c(0,0), limits = c(min(df$y), max(df$y)))\nRun Code Online (Sandbox Code Playgroud)\n然后,我们设置轴标题的格式。为了获得更好的视觉表现,我还添加了边距,将标题稍微移离轴线。
\ngraph <-\n graph +\n theme(\n axis.title.x = element_text(hjust = 0, margin = margin(t=6)),\n axis.title.y = element_text(angle = 90, hjust = 1, margin=margin(r=6))\n )\nRun Code Online (Sandbox Code Playgroud)\n最后,我们添加轴标题:
\ngraph <-\n graph +\n xlab("This is the x axis") + \n ylab("This is the y axis")\nRun Code Online (Sandbox Code Playgroud)\n结果:
\n\n但是,这会切断最后一个标签文本(100 中的最后 0 仅部分可见)。为了解决这个问题,我们必须增加绘图边距,这里以所有边的边距为 1 厘米为例:
\ngraph <-\n graph +\n theme(plot.margin = margin(1, 1, 1, 1, "cm"))\nRun Code Online (Sandbox Code Playgroud)\n最终结果:
\n\nlibrary(ggplot2)\n\n\ndf <- data.frame(\n x = c(0, 50, 100),\n y = c(20, 40, 80)\n)\n\ngraph <-\n ggplot(data=df, mapping = aes(x=x, y=y)) +\n geom_line() +\n expand_limits(x = 0, y = 0) +\n scale_x_continuous(expand = c(0,0), limits = c(min(df$x), max(df$x))) +\n scale_y_continuous(expand = c(0,0), limits = c(min(df$y), max(df$y))) +\n theme(\n axis.title.x = element_text(hjust = 0, margin = margin(t=6)),\n axis.title.y = element_text(angle = 90, hjust = 1, margin=margin(r=6)),\n plot.margin = margin(1, 1, 1, 1, "cm")\n ) +\n xlab("This is the x axis") + \n ylab("This is the y axis")\n \n \nRun Code Online (Sandbox Code Playgroud)\n