我想制作一个带有标签的水平条形图,在它们的“基础”上
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)
)
Run Code Online (Sandbox Code Playgroud)
如何将这些标签移动到每个条形的“基础”?每个州名称的左侧应位于条形图的左侧。
如果您使用闪避来帮助定位,则没有必要。此外,还可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())
Run Code Online (Sandbox Code Playgroud)
但是,请考虑使用geom_segment()which 可以让您获得更多控制并且不需要翻转:
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())
Run Code Online (Sandbox Code Playgroud)