如何将条形图标签放置在条形的“底部”

时间:2018-09-17 21:52:28

标签: r ggplot2

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

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

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

2 个答案:

答案 0 :(得分:3)

如果您使用躲避来尝试帮助定位,则没有必要。另外,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

答案 1 :(得分:1)

也许是这样吗?

+ geom_text(aes(label = state,y = 0),
          position = position_dodge(1),
          hjust = 0)