【问题标题】:Horizontal bar graph with ggplot: Fixed distance of bars带有ggplot的水平条形图:条的固定距离
【发布时间】:2020-11-12 12:37:13
【问题描述】:

这个问题与我在这里已经问过的问题有关:Properly align country names and values for horizontal bar graph in ggplot

我想制作以下条形图,但想确保从国家名称的开头到条形图的距离始终相同。所以无论我读的是第一个还是第二个df,它应该总是和这里一样的距离:

#df1
loooooong country1   100% Bar
looooong country2     99% Bar

#df2
short country1       100% Bar
short country2        99% Bar


就目前而言,国名末尾和小节之间的距离始终相同。我找到了一种解决方法,用空格填充国家名称并使用等宽字体,但这看起来很糟糕.. :)


library(ggplot2)
library(dplyr)


### first df
df <- data.frame(
  info_country = c("country1", "country loooooooong name", "country2", "country middle name", "country3"),
  indicator = c(50,100,50,50,5))

### second df
# df <- data.frame(
#   info_country = c("country1", "country3", "country2", "country4", "country5"),
#   indicator = c(50,100,50,50,5))

### change factor level for ggplot order
df$info_country <- factor(df$info_country, levels = df$info_country[order(df$indicator)])
factor(df$info_country)


### create bar graph
bar_graph <- df %>%
  ggplot( aes(x = info_country, y = indicator)) + 
  geom_bar(stat = "identity", width = 0.8, fill = "#EE5859") +
  geom_text(aes(y = -2, label = paste(indicator, "%", sep=" ")), 
            hjust = 1, size = 11 * 0.8 / ggplot2::.pt, color = "grey30") +
  xlab("") + 
  ylab("") + 
  scale_y_continuous(labels = NULL, limits = c(-2, 100)) +
  # Use clip = "off" to prevent that percentage labels are clipped off
  coord_flip(clip = "off") + 
  theme(
    panel.background = element_rect(fill = "white", colour = NA), 
    # Set color of ticks to NA
    axis.ticks.x = element_line(color=NA), 
    axis.ticks.y = element_line(color=NA),
    # Increase the margin 
    axis.text.y = element_text(hjust=0, margin = margin(r = 6, unit = "cm")),
    axis.text.x = element_text(hjust=0),
  )

bar_graph

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我会简单地重复绘制文本的技巧,就好像它是轴标签一样。您可以通过将标签的 hjust 设置为 0 并在其美学中为 y 使用较大的负数来控制标签左边缘与条形起点之间的距离。 -100 的值非常对称:

    df %>%
      ggplot( aes(x = info_country, y = indicator)) + 
      geom_bar(stat = "identity", width = 0.8, fill = "#EE5859") +
      geom_text(aes(y = -2, label = paste(indicator, "%", sep=" ")), 
                hjust = 1, size = 11 * 0.8 / .pt, color = "grey30") +
      geom_text(aes(y = -100, label = info_country), 
                hjust = 0, size = 11 * 0.8 / .pt, color = "grey30") +
      labs(x = "", y = "") + 
      scale_y_continuous(labels = NULL, limits = c(-100, 100)) +
      coord_flip(clip = "off") + 
      theme(panel.background = element_rect(fill = "white", colour = NA), 
            axis.ticks.x = element_line(color = NA), 
            axis.ticks.y = element_line(color = NA),
            axis.text.y = element_blank())
    

    【讨论】: