1

here's my problem:

with this simple example dataframe:

Samples =  c("SRR9292593", "SRR9292593", "SRR9292593", "SRR9292594", "SRR9292594", "SRR9292594")
expression_gene = c(3.5, 0.4, 8.2, 4.5, 3.2, 3.1)
expression_intron = c(0.1, 0.1, 0.1, 0.5, 0.5, 0.5)
p <- data.frame(Samples, expression_gene, expression_intron)

I would like to make a boxplot with 2 x-axes, one indicating the values in "Samples", the other with the respective values in "expression_intron".

I tried this:

ggplot(p, aes(x=reorder(Samples, expression_intron), y=expression_gene)) + 
       geom_boxplot(color="black") +
       scale_x_continuous(sec.axis = sec_axis(~ . * 1, breaks = c("SRR9292593", "SRR9292594"), labels = c("0.1","0.5")))

But it gives me this error:

Error: Discrete value supplied to continuous scale

How could i fix this?

Thanks in advance for the answers.

1 Answers1

2

I think we can adapt Duplicating (and modifying) discrete axis in ggplot2 to force the x-axis to be continuous; I say "adapt" because when we convert Samples to a factor and use as.numeric(Samples), it produces a single boxplot; we need to add group= to get it to split as needed.

Note that this requires a perfect 1-to-1 between Samples and expression_intron; anything else doesn't quite make sense in the perspective of your plotting request.

I'll demo with dplyr, but this can easily be adapted to base R if needed.

library(dplyr)
p2 <- p %>%
  mutate(
    Samples = reorder(Samples, expression_intron),
    expression_intron = factor(expression_intron)
  )

ggplot(p2, aes(x = as.numeric(Samples), y = expression_gene, group = Samples)) +
  geom_boxplot(color="black") +
  scale_x_continuous(
    # assign breaks/labels to convert our numerics to discrete labels
    breaks = seq_along(levels(p2$Samples)),
    labels = levels(p2$Samples),
    sec.axis = sec_axis(
      ~ .,
      name = "expression_intron",
      # this could be seq_along(levels(p2$expr...)) as well, same thing
      breaks = seq_along(levels(p2$Samples)),
      labels = levels(p2$expression_intron)
    )
  ) +
  labs(x = "Samples")

ggplot boxplot, discrete with second axis also discrete

r2evans
  • 141,215
  • 6
  • 77
  • 149