【发布时间】:2017-05-11 14:42:58
【问题描述】:
我希望设置一个中间有一组轴标签的镜像条形图。这张图片显示了我到目前为止的内容(最后重现的代码):
我希望名称在图表之间居中。尝试的方法:
- 使用轴标签(此处显示最佳尝试)
- 使用
annotation_custom(我发现放置标签非常困难,并且不喜欢 ggplot 参考和基础绘图参考的组合) - 创建一个单独的“图表对象”以放入 grid.arrange 面板(如果没有任何条,很难在标签之间获得正确的垂直间距)
我欢迎任何有关实现此布局的最简单方法的建议。 base 必须是 ggplot,但乐于使用其他包来排列图表。
require("ggplot2")
require("gridExtra")
dataToPlot <- data.frame(
"Person" = c("Alice", "Bob", "Carlton"),
"Age" = c(14, 63, 24),
"Score" = c(73, 62.1, 21.5))
plot1 <- ggplot(dataToPlot) +
geom_bar(data = dataToPlot, aes(x = Person, y = Score), stat = "identity",
fill = "blue", width = 0.8) +
scale_y_continuous(trans = "reverse", expand = c(0, 0)) +
scale_x_discrete(position = "top") +
theme(
axis.text.y = element_blank()
) +
labs(x = NULL) +
coord_flip()
plot2 <- ggplot(dataToPlot) +
geom_bar(data = dataToPlot, aes(x = Person, y = Age), stat = "identity",
fill = "red", width = 0.8) +
scale_y_continuous(expand = c(0, 0)) +
theme(
axis.text.y = element_text(size = 20, hjust = 0.5)
) +
labs(x = "") +
coord_flip()
gridExtra::grid.arrange(plot1, plot2, ncol = 2, widths = c(1, 1.2))
【问题讨论】:
-
element_text(size = 20, hjust = 0.5)应该居中 -
谢谢 - 好地方。这使它们居中,但我也想将它们从轴上移一点。我将发布具有正确 hjust 值的更新图像。
-
您可能需要调整值,但
element_text(size = 20, hjust = 0.5,margin=margin(r=30))或多或少对我有用。 -
太完美了——谢谢。我不知道我可以在
element_text对象中使用边距。如果您想在答案中弹出该行,我会为您的代表接受它 -
或者——甚至更好——尝试在
grid.arrange中设置padding=0