Home > Mobile >  Log Scaling ggplot2 values above and below 1 axis starting at min point
Log Scaling ggplot2 values above and below 1 axis starting at min point

Time:06-14

I am trying to get this bar graph-oriented from the lowest to the highest value with log10 normalized values so all values are present. The problem I am running into is numbers below 1 are showcased as 10^-negative and plot differently than values above 1 (10^positive).

The only solutions I found were to use geom_segment, but there isn't a solution to do this with character values in the x position as my data is structured.

How can I have this graphic show values from 0.0001 to 100 all in log scale?

dt <- read.csv("data_median.csv")

# load ggplot2
library(ggplot2)
library(hrbrthemes)
library(tidyverse)
library(dplyr)
library(ggallin)
library(scales)

quantile_plot <- ggplot(dt, aes(x = Label, y = y, color = Type))  
            geom_bar(stat = "identity")  
            labs(title = 'Contaminant_plot', y = 'ng/g Wet Weight')  
            scale_y_continuous(trans= 'log10')  
            theme(text = element_text(size = 10))  
            scale_fill_brewer(palette = "Set1")   
            coord_flip()

quantile_plot

#save to plots to disk
  ggsave("Contaminant_Plot.png", width = 45.5, height = 27.78, units = 'cm', dpi = 600)

graphic

CodePudding user response:

The tricky part here is that mathematically it's producing exactly the right thing. You could transform it slightly by dividing each value by the minimum to set the '0' point as the minimum value, and have everything facing the right way:

library(tidyverse)

df <- tibble(a = letters[1:15],
       b = 10^rnorm(15)) 

df |> 
  ggplot(aes(y = a, x = b))  
  geom_bar(stat = "identity")  
  scale_x_log10()

... becomes:

df |> 
  mutate(trans_b = b/ min(b)) |> 
  ggplot(aes(y = a, x = trans_b))  
  geom_bar(stat = "identity")  
  scale_x_log10()

Of course, that only gives a relative scale, saying for instance "o is ~10 times the size of l". Another solution would be to change your units so they're all above 1 before scaling:

  
df |> 
  mutate(trans_b = b*1000) |> 
  ggplot(aes(y = a, x = trans_b))  
  geom_bar(stat = "identity")  
  scale_x_log10("B's per 1,000")

Created on 2022-06-13 by the enter image description here

  • Related