I have this table (T_Tornado_Total_EM_HM_sort):
And these are the lines that I used to make the tornado chart:
ggplot(T_Tornado_Total_EM_HM_sort, aes(Tipovi_troškova, RSD, fill=Populacija)) +
coord_flip() + geom_bar(stat="identity") + scale_y_continuous(labels=human_numbers) +
geom_text(aes(label = format(floor(RSD), big.mark=",")), position = position_dodge(width = -1, preserve = "total"), size = 3)
This is the chart:
I have several questions, hoping anyone can help me:
Is it possible to make values next to bars in a way that the ones on the right side (for red bars) go slightly right (outside) of the bars, but next to them, and the ones on the left side (for blue bars) go left of the bars (outside), (and what would be the version of the code if putting the leading lines from bars to values)?
How can I reorder bars in a way that on the top of the chart there are the biggest values, going down in a decreasing way? I managed to make decreasing order in the table, but the chart is ignoring it, putting its own order.
Can the name for y-axis (Tipovi_troškova) be with space instead of the underscore? I tried to put space and put the name under "" in aes() function but this ruins the whole chart.
Can anyone help me with this? I would be very grateful. Thank you in advance!
To your main question, you can precompute a positive or negative justification parameter based on your grouping variable, then map this to hjust
. Reorder your bars based on values using reorder()
or forcats::fct_reorder()
. The easiest way to include a space in the axis label is by specifying the label inside labs()
, xlab
/ ylab()
, or the appropriate scale_
function. The other option is to rename your column and refer to it using backticks.
library(ggplot2)
# compute right or left justification
dat$lab_hjust <- ifelse(dat$group == "a", -0.1, 1.1)
# order factor levels by value
dat$category_label <- reorder(dat$category_label, dat$value, FUN = \(x) sum(abs(x))) l
ggplot(dat, aes(value, category_label, fill = group)) +
geom_col() +
geom_text(
aes(
label = format(floor(value), big.mark=","),
# map `hjust` to computed hjust
hjust = lab_hjust
),
size = 3
) +
scale_x_continuous(
label = scales::comma,
# expansion to accommodate labels
expand = expansion(mult = .25)
) +
# set axis label
labs(y = "Category Label")
Example data:
set.seed(13)
dat <- data.frame(
category_label = rep(LETTERS[1:12], each = 2),
group = rep(c("a", "b"), 2),
value = rnorm(24, 2e8, 1e8)
)
dat$value <- abs(dat$value) * ifelse(dat$group == "a", 1, -1)