我正在尝试将x标签放在geom_bar上,使它们垂直,在条形图的顶部,并与条形图的底部对齐。我得到了前两个,但不是最后一个。
data(mpg)
mpg <- mpg
这样可以按照我想要的方式证明文本(左/底对齐)
ggplot(mpg, aes(x=interaction(manufacturer, year), y=hwy, fill=manufacturer)) +
geom_bar(stat="identity", width = 1, color="black") +
theme(axis.text.x = element_text(angle = 90, size = 5, hjust=0, vjust=-.05))
这会将文字放得更高,以便覆盖条形图,但它并不是我想要的方式,每个标签都从x轴开始。
ggplot(mpg, aes(x=interaction(manufacturer, year), y=hwy, fill=manufacturer)) +
geom_bar(stat="identity", width = 1, color="black") +
theme(axis.text.x = element_text(angle = 90, size = 5, hjust=3, vjust=-.05))
我也玩过margin = margin(#,#,#,#),我无法辨别出任何影响。我还能尝试什么?
答案 0 :(得分:4)
您可以使用geom_text
和stat = "summary"
添加标签,scale_y_continuous
来调整y轴的大小:
library(ggplot2)
ggplot(mpg, aes(interaction(manufacturer, year), hwy,
fill = manufacturer, label = interaction(manufacturer, year))) +
geom_col(width = 1, color = "black") +
geom_text(stat = 'summary', fun.y = sum, angle = 90, hjust = -.05, size = 2) +
scale_y_continuous(limits = c(0, 575), expand = c(0, 0)) +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank())
或者如果您想要每个栏底部的文字,只需将y
设为0:
ggplot(mpg, aes(interaction(manufacturer, year), hwy, fill = manufacturer, label = interaction(manufacturer, year))) +
geom_col(width = 1, color = "black") +
geom_text(aes(y = 0), angle = 90, hjust = -.05, size = 2) +
scale_y_continuous(limits = c(0, 500), expand = c(0, 0)) +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank())