Cyrillm_44
Cyrillm_44

Reputation: 711

ggplot with col and fill

I am producing a residual bubble plot, and want color's to represent positive and negative, and if the value is large say >3 then I want the fill to be gray otherwise keep the fill as the default color. This is what I have got so far.

set.seed(123)
library(ggplot2)
library(reshape2)

resids_matrix = matrix(rnorm(100,0,1.2), nrow  = 10)
dimnames(resids_matrix) = list(1:10, 1:10)
## reformat data
df_melted = reshape2::melt(resids_matrix)
df_melted$year = df_melted$Var1
df_melted$variable = df_melted$Var2
df_melted$large_resid = abs(df_melted$value) >= 3
df_melted$sign = df_melted$value <= 0
df_melted$plotted_var = df_melted$value
df_melted$plotted_var[df_melted$plotted_var < -3] = -3
df_melted$plotted_var[df_melted$plotted_var > 3] = 3

ggplot(df_melted, aes(x = year, y = variable, size =  abs(plotted_var), col = sign, fill = large_resid)) +
geom_point() + 
scale_colour_manual(name = 'Sign', values = c("#F8766D", "#00BFC4"), label = c("Negative", "Positive")) +
scale_fill_manual(name = 'Outliers', values = c(ifelse(sign, "#F8766D", "#00BFC4"),"gray60"), labels = c("less than 3", "greater than 3"))

but I am stumped on how to apply the scale_fill_manual code, thanks in advance

Upvotes: 1

Views: 284

Answers (1)

TobiO
TobiO

Reputation: 1381

For illustration purposes I set the upper limit to 2, because values out of [-3,3] are rare

set.seed(123)
library(ggplot2)
library(reshape2)

resids_matrix = matrix(rnorm(100,0,1.2), nrow  = 10)
dimnames(resids_matrix) = list(1:10, 1:10)
## reformat data
df_melted = reshape2::melt(resids_matrix)
df_melted$year = df_melted$Var1
df_melted$variable = df_melted$Var2
df_melted$large_resid = abs(df_melted$value) >= 3
#df_melted$sign = df_melted$value <= 0 #can lead to mixups, because levels "TRUE" and "FALSE" are generated and have different alphabetical order than their "Positive" and "Negative" counterparts
df_melted$sign = ifelse(df_melted$value <= 0,"Negative","Positive")
df_melted$fillcolor=ifelse(df_melted$value>=2,"larger than 2",
                           ifelse(df_melted$value<=-3,"less than -3",
                                  ifelse(df_melted$value <= 0,"Negative","Positive")))
df_melted$plotted_var = df_melted$value
df_melted$plotted_var[df_melted$plotted_var < -3] = -3
df_melted$plotted_var[df_melted$plotted_var > 3] = 3

ggplot(df_melted, aes(x = year, y = variable, size =  abs(plotted_var), col = sign, fill = fillcolor)) +
  geom_point(shape=21) + #this shape actually has a fill ;-)
  scale_colour_manual(name = 'Sign', values = c("Positive"="#F8766D", "Negative"="#00BFC4")) +
  scale_fill_manual(name="Outliers",values=c("larger than 2"="gray60","less than 3"="gray60",
                                             "Positive"="#F8766D","Negative"="#00BFC4")) #make sure names match the levels in "fillcolorby"

enter image description here

Upvotes: 1

Related Questions