r - 如何使用 position_nudge 将 x 轴标签与 ggplot2 中的条形中心对齐
问题描述
在我的原始图中,最靠近 y 轴的条形与 y 轴重叠。我使用了 position_nudge 确实移动了条,但现在我无法将 x 轴标签与新定位的条对齐。未对齐的 x 轴标签的图片
# data frame
AV_sum <- data.frame(condition = c( "Braced", "Unbraced"),
AvgVelocity = c(-1, -3),
se = c( 0.5, 0.3)
)
p <- ggplot(AV_sum, aes(x =condition, y = abs(AvgVelocity), fill = condition)) +
ggtitle("Average Velocity Between Conditions") +
geom_bar(position=position_nudge(0.5), colour = "black", stat="identity") +
geom_errorbar(aes(ymin=abs(AvgVelocity), ymax = abs(AvgVelocity)+se),
width = 0.1, colour = "black", position = position_nudge(0.5)) +
theme_classic() + xlab("Condition") +
ylab("Average Velocity") +
theme(plot.title = element_text(colour =
"black", size = 18, face = "bold", hjust = 0.5), legend.position=
"none", axis.text = element_text(colour = "black", size= 12, face =
"bold"), axis.title = element_text(size = 14, face = "bold"))
p +
scale_fill_manual(values = c( "white", "black")) +
coord_cartesian(ylim = c(0, 5), expand = FALSE) +
labs(fill = ("")) +
scale_y_continuous(breaks = seq(0, 5, 0.5)) +
geom_text(x = 2.0, y = 4, label = "***", size = 12)
解决方案
我担心你用轻推使事情过于复杂。您的一个条与 y 轴发生碰撞的原因是由于expand = FALSE
in coord_cartesian()
。
我最好的猜测是,您想防止条形图和 x 轴之间出现尴尬的间隙。如果是这种情况,我会建议调整expand
内部的参数scale_y_continuous()
。
我已将您的代码重写为我认为您所追求的:
ggplot(AV_sum, aes(x =condition, y = abs(AvgVelocity), fill = condition)) +
ggtitle("Average Velocity Between Conditions") +
# Deleted nudges, use geom_col, which is equivalent to geom_bar(stat = "identity")
geom_col(colour = "black") +
geom_errorbar(aes(ymin=abs(AvgVelocity), ymax = abs(AvgVelocity)+se),
width = 0.1, colour = "black") +
geom_text(x = 1.5, y = 4, label = "***", size = 12) +
# Moved expand from coord_cartesian to scale_y_condintuous
coord_cartesian(ylim = c(0, 5)) +
scale_x_discrete(name = "Condition") +
scale_y_continuous(breaks = seq(0, 5, 0.5), expand = c(0,0), name = "Average Velocity") +
scale_fill_manual(values = c( "white", "black")) +
theme_classic() +
theme(
plot.title = element_text(colour = "black", size = 18, face = "bold", hjust = 0.5),
legend.position = "none",
axis.text = element_text(colour = "black", size= 12, face = "bold"),
axis.title = element_text(size = 14, face = "bold")
)
关于 Tjebo 的评论,我通常发现构建 ggplot 代码最容易将执行类似操作的函数组合在一起,例如将几何图形组合在一起、组合坐标和(位置)比例以及组合主题调整。由于主题论点有时会变得庞大,我建议给每个论点单独一行。
推荐阅读
- swift - 通过向左滑动选择 CollectionView 单元格(Swift 5)
- sql-server - 如何查询包含单引号的数据库字段?
- java - 为什么在这两种情况下 unicode 编码不同?
- javascript - 基于另一个参数约束参数类型的最有效方法
- bash - 删除文件中的行直到特定行
- javascript - 根据选项隐藏/显示 DIV 不起作用
- javascript - 使用中继器 asp.net 网络表单尝试动态轮播滑块
- ios - 如何在 UICollectionViewCell 中有一个自动换行标签,其右锚点约束到单元格的右锚点?
- groovy - 如何禁用groovyscript中的警告?
- github - Sonarqube 徽章在 github README 上不起作用