ggplot的水平条形图:条形的固定距离

时间:2020-11-12 12:37:13

标签: r ggplot2

这个问题与我在这里已经问过的问题有关: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

1 个答案:

答案 0 :(得分: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())

enter image description here

相关问题