【发布时间】: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
【问题讨论】: