Mike
Mike

Reputation: 1151

geom_bar originates from the top of the plot when using a log2 scaled y-axis

When I log2 scale my y-axis, the bars from geom_bar originate at the top. How do I make them originate from the bottom, like a normal graph?!

data <- structure(list(EV_isolation = c(NA, NA, NA, NA, NA, NA, NA, "Neat", 
"Neat", "Neat", "Neat", "Neat", "UF10", "UF10", "UF10", "SEC + UF10", 
"SEC + UF10", "SEC + UF10", "Neat", "Neat", "Neat", "Neat", "Neat", 
"Neat", "UF10", "UF10", "UF10", "SEC + UF10", "SEC + UF10", "SEC + UF10"
), conc_ngul_Small = c(61.1084583702352, 2.4526480455757, 0.524585334390034, 
0.0632839195654501, 0.00832448970211358, NA, 1.68155673229734e-05, 
3.97138430754394e-06, 1.81792184263953e-05, 3.06636699250652e-06, 
2.11538793836442e-05, 0.000229824972979194, 5.38527417344961e-06, 
2.4010537183241e-06, 0.0033191762123805, 2.09333351213478e-06, 
4.07067991649057e-07, 2.2189384059898e-05, 1.61025682351412e-06, 
1.99057376776679e-06, 1.08135890720553e-05, 0.0928861355883511, 
2.7535231093519e-05, 0.00163511453610949, 5.40114433428359e-06, 
7.07038486618358e-07, 0.0271561234396818, NA, 5.47078031782244e-07, 
7.9672201702889e-05)), row.names = c(NA, -30L), class = c("tbl_df", 
"tbl", "data.frame"))

ggplot(data, aes(x = EV_isolation, y = conc_ngul_Small)) +
  geom_bar(stat = "identity") +
  scale_y_continuous(trans="log2")

enter image description here

Upvotes: 1

Views: 28

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174278

I would explicitly log-transform the data before plotting, then add a fixed amount to take all of the log values above zero. Then, apply a labelling function that reverses this transformation.

Note I have summed the multiple values here first, since stacking doesn't make any sense here; you can skip this step if you are using facets as per the comments.

library(tidyverse)

data %>%
  group_by(EV_isolation) %>%
  summarise(conc_ngul_Small = sum(conc_ngul_Small, na.rm = TRUE)) %>%
  mutate(conc_ngul_Small = log10(conc_ngul_Small) + 5) %>%
  ggplot(aes(x = EV_isolation, y = conc_ngul_Small)) +
  geom_col(fill = "deepskyblue4", color = "black") +
  scale_y_continuous(breaks = 0:7, labels = ~ 10^(.x - 5)) +
  labs(y = bquote(Concentration~(ngl^-1))) +
  theme_minimal(base_size = 20)

enter image description here

Upvotes: 1

Related Questions