Sto*_*aft 3 r ggplot2 geom-bar
我试图在 geom_bar 上放置 x 标签,使它们垂直,在条形图的顶部,并与条形图的底部对齐。我得到了前两个,但不是最后一个。
data(mpg)
mpg <- mpg
Run Code Online (Sandbox Code Playgroud)
这会按照我想要的方式证明文本的合理性(左/下对齐)
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))
Run Code Online (Sandbox Code Playgroud)
这会将文本放在更高的位置,以便它覆盖条形,但它不是我想要的方式,每个标签都从 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))
Run Code Online (Sandbox Code Playgroud)
我也玩过 margin=margin(#,#,#,#),我看不出有任何影响。我还能尝试什么?
您可以使用geom_textwithstat = "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())
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望每个条形底部的文本,只需设置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())
Run Code Online (Sandbox Code Playgroud)