r - 将轴标题与轴边缘完美对齐
问题描述
对于ggplot2
绘图,hjust
和vjust
是相对于整个绘图定义的对齐函数。因此,当它们应用于轴标签时,它们不是相对于轴线定义的。
但是,相对于轴线调整轴标题更为自然。
具体来说,我正在寻找一种左对齐x
轴标题以及顶部对齐和旋转y
轴标题的方法。
怎么能做到这一点?
解决方案
如问题中所述,hjust
并且vjust
是相对于整个图定义的对齐函数。
因此,hjust=0
将不会实现相对于x
轴线起点的完美左对齐。但是,它可以与expand_limits
和结合使用scale_x_continuous
。
与轴标题类似scale_y_continuous
。y
在问题的附加图像中,情节从原点开始。所以首先,我们必须强制情节从原点开始:
... +
expand_limits(x = 0, y = 0) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0))
然后我们可以指定调整——这里还添加了y
轴标题的旋转,这需要我们使用hjust
而不是vjust
:
... +
theme(
axis.title.x = element_text(hjust = 0),
axis.title.x = element_text(angle = 90, hjust = 1)
)
完整的工作示例
首先,我们加载ggplot2
并创建一个数据集:
library(ggplot2)
df <- data.frame(
x = c(0, 50, 100),
y = c(20, 40, 80)
)
我们创建情节并添加一个geom_line()
.
graph <-
ggplot(data=df, mapping = aes(x=x, y=y)) +
geom_line()
我们修复我们的轴。作为更好地控制轴的额外奖励,我还定义了轴范围 ( limits
)。
graph <-
graph +
scale_x_continuous(expand = c(0,0), limits = c(min(df$x), max(df$x))) +
scale_y_continuous(expand = c(0,0), limits = c(min(df$y), max(df$y)))
然后,我们格式化轴标题。为了更好的视觉表现,我还添加了一个边距,使标题稍微远离轴线。
graph <-
graph +
theme(
axis.title.x = element_text(hjust = 0, margin = margin(t=6)),
axis.title.y = element_text(angle = 90, hjust = 1, margin=margin(r=6))
)
最后,我们添加轴标题:
graph <-
graph +
xlab("This is the x axis") +
ylab("This is the y axis")
结果:
但是,这会切断最后一个标签文本(100 中的最后一个 0 仅部分可见)。为了解决这个问题,我们必须增加绘图边距,这里以四周 1 厘米的边距为例:
graph <-
graph +
theme(plot.margin = margin(1, 1, 1, 1, "cm"))
最终结果:
完整代码
library(ggplot2)
df <- data.frame(
x = c(0, 50, 100),
y = c(20, 40, 80)
)
graph <-
ggplot(data=df, mapping = aes(x=x, y=y)) +
geom_line() +
expand_limits(x = 0, y = 0) +
scale_x_continuous(expand = c(0,0), limits = c(min(df$x), max(df$x))) +
scale_y_continuous(expand = c(0,0), limits = c(min(df$y), max(df$y))) +
theme(
axis.title.x = element_text(hjust = 0, margin = margin(t=6)),
axis.title.y = element_text(angle = 90, hjust = 1, margin=margin(r=6)),
plot.margin = margin(1, 1, 1, 1, "cm")
) +
xlab("This is the x axis") +
ylab("This is the y axis")
推荐阅读
- javascript - RecordRTC 错误:MediaRecorder API 似乎无法录制 mimeType:audio/wav
- c# - jquery ajax 发布数据在控制器处始终为 Null
- android - 用于延迟加载 RecyclerView 的 ScrollToPosition
- java - Kotlin BigInteger 到 BigDecimal 的转换
- asp.net-mvc - 为什么在 MVC/API 应用程序中从 URL 中删除控制器后缀
- callback - 奇怪的回调调用语法(需要解释)
- python - 将 virtualenv 移动到另一台具有不同 python 版本的 PC
- reactjs - 在构造函数中与在构造函数外声明 React 状态
- c - C 函数 (fgets) 缓解
- clojure - `loop` 和 `with-redefs` 不能很好地配合使用