gpt4 book ai didi

r - 如何将条形图标签定位在条形的 "base"

转载 作者:行者123 更新时间:2023-12-01 22:05:11 28 4
gpt4 key购买 nike

我想制作一个水平条形图,在条形图的“底部”带有标签

dummy <- USArrests
dummy$state <- rownames(USArrests)

ggplot(
data = dummy,
aes(
x = state,
y = Murder
)
) +
geom_bar(
stat = "identity"
) +
coord_flip() +
geom_text(
aes(
label = state
),
position = position_dodge(1)
)

这为我提供了一个图表,其中标签位于每个条形的“尖端”。 enter image description here

如何将这些标签移动到每个栏的“底部”?每个州名称的左侧应位于条形图的左侧。

最佳答案

如果您使用闪避来尝试帮助定位,则没有必要。此外,geom_col() 可以为您节省一些输入:

library(hrbrthemes) # devtools::install_git("https://gitlab.com/hrbrmstr/hrbrthemes")
library(ggplot2)

set.seed(1)
data.frame(
state = state.name,
murder = sample(1000, length(state.name)),
stringsAsFactors = FALSE
) -> xdf

ggplot(xdf, aes(state, murder)) +
geom_col(fill = "#2b2b2b") +
geom_text(
aes(y = 0, label = state),
color = ft_cols$yellow, hjust = 0
) +
scale_y_continuous(
expand=c(0,0), label=scales::comma, position = "right"
) +
coord_flip() +
labs(x = NULL) +
hrbrthemes::theme_ipsum_rc(grid="X") +
theme(axis.ticks.y = element_blank()) +
theme(axis.text.y = element_blank())

enter image description here

但是,请考虑使用 geom_segment(),它可以让您有更多的控制权并且不需要翻转:

ggplot(xdf, aes(murder, state)) +
geom_segment(
aes(xend=0, yend=state),
size = 5, color = "#2b2b2b"
) +
geom_text(
aes(x = 0, label = state),
color = ft_cols$yellow, hjust = 0
) +
scale_x_continuous(
expand=c(0,0), label=scales::comma, position = "top"
) +
labs(y= NULL) +
hrbrthemes::theme_ipsum_rc(grid="X") +
theme(axis.ticks.y = element_blank()) +
theme(axis.text.y = element_blank())

enter image description here

关于r - 如何将条形图标签定位在条形的 "base",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52376169/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com