Reputation: 93
I am creating graphs below based on data that I simulated. The data consists of two groups, A and B, each with different values drawn from different distributions. When I use the code below to create a stripplot graph, the range of the color scale changes for each simulated graph. For example, dark red for the top image maps to 90 compared to 120 in the bottom image. I need the colors to map to the same values throughout the creating of all of the graphs.
## GGPLOT: Ensemble Stripplts ##
for(i in 1:max(unique(saveDT$iter))){
#grab the data for this dataset
gg<-saveDT[which(saveDT$iter==i),]
gg$group<-factor(gg$group)
# set the limits of the palette so that zero is in the middle of the range.
# png(paste0("aggIndividGroupV1","-",sa,".png"), width = 400, height = 300)
# par(mar=c(1, 1, 1, 1))
print(ggplot(gg, aes(x=i, y=1,fill=value)) + facet_grid(. ~ group)+
theme(strip.background = element_rect(color="white", fill="white"))+
geom_vline(aes(xintercept = value, lwd=5, color=value))+
scale_colour_gradientn(colours=rev(brewer.pal(9,"RdBu"))))
}
Q1: How do I fix the color scale?
Q2: How can I change the midpoint value to represent a specific fixed midpoint?
Q3: Why does ggplot() make the RdBu brewer color palette look significantly different than when using RdBu in the plot() function? (see last image for comparison). Plot() seems to make them look more saturated and less of a gradient. I've tried to use the code scale_fill_divergentx() but this and other types do not work with my ggplot() function.
Upvotes: 2
Views: 150
Reputation: 10365
You can set the limits of the colour scale with limits
within scale_colour_gradientn
. This also fixes the midpoint. Here I set the limits from 40 to 120, meaning the midpoint is 80.
library(ggplot2)
#> Warning: replacing previous import 'vctrs::data_frame' by 'tibble::data_frame'
#> when loading 'dplyr'
library(RColorBrewer)
set.seed(4)
gg <- data.frame(value = runif(20, min = 40, max = 120),
group = rep(c("A", "B"), each = 10))
print(ggplot(gg, aes(y=1, fill=value)) + facet_grid(. ~ group)+
theme(strip.background = element_rect(color="white", fill="white"))+
geom_vline(aes(xintercept = value, color=value), size = 5)+
scale_colour_gradientn(colours = rev(brewer.pal(9,"RdBu")),
limits = c(40, 120)))
gg <- data.frame(value = runif(20, min = 60, max = 80),
group = rep(c("A", "B"), each = 10))
print(ggplot(gg, aes(y=1,fill=value)) + facet_grid(. ~ group)+
theme(strip.background = element_rect(color="white", fill="white"))+
geom_vline(aes(xintercept = value, color=value), size = 5)+
scale_colour_gradientn(colours = rev(brewer.pal(9,"RdBu")),
limits = c(40, 120)))
Created on 2020-10-30 by the reprex package (v0.3.0)
Thanks @Rui Barradas for the improvements!
Upvotes: 2