0

How to give colors based on the Y axis values in my geom_violin? I would like to show that factors with larger y values have a more intense blue and factors with smaller y values have a less intense red. I would like to keep that color palette. Please can someone help me?

I have de following script in R:

ggplot(df4, aes(x =orden, y = size, fill = orden)) +
  geom_violin(trim = FALSE) +
  scale_fill_brewer(palette="RdBu")+
  geom_boxplot(width = 0.07) +   
  scale_x_discrete(labels = c("Insectos palo","Hormigas", "Escarabajos",
                                "Áfidos", "Moscas", "Mariposas", "Polillas", 
                                "Saltamontes")) +
  labs(x=c(""),y="Tamaño del genoma (Mb)")+
  #scale_y_continuous(trans = "log2")+#, breaks = c(20, 40, 80))
  theme_classic()

enter image description here

Many thanks

  • 1
    It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Jul 07 '22 at 15:38

1 Answers1

2

Try this. I've put alpha in the geom_violin to vary the intensity of that geom.

library(tidyverse)
library(RColorBrewer)

# Made-up data
df <- tribble(
  ~orden, ~size,
  1, 1,
  1, 2,
  1, 1.2,
  2, 1.7,
  2, 1.3,
  2, 1.5,
  3, 4.7,
  3, 4.3,
  3, 5.5
) 

# Plot
df |>
  group_by(orden) |> 
  mutate(orden = factor(orden),
         alpha = mean(size)) |> 
  ungroup() |> 
  ggplot(aes(orden, size, fill = orden)) +
  geom_violin(aes(alpha = alpha), trim = FALSE) +
  scale_fill_brewer(palette = "RdBu") +
  geom_boxplot(width = 0.07) +
  scale_x_discrete(labels = c(
    "Insectos palo", "Hormigas", "Escarabajos",
    "Áfidos", "Moscas", "Mariposas", "Polillas",
    "Saltamontes"
  )) +
  labs(x = NULL, y = "Tamaño del genoma (Mb)", fill = "orden") +
  theme_classic() +
  guides(alpha = "none")

Created on 2022-07-07 by the reprex package (v2.0.1)

Carl
  • 4,232
  • 2
  • 12
  • 24