logo
down
shadow

ggplot2 scale colours for heatmap


ggplot2 scale colours for heatmap

By : techieShams
Date : November 21 2020, 11:01 PM
With these it helps [REVISION]
In scale_fill_gradientn(), it is needed that length(colours) and length(values) are the same. You can calculate values easily using scales::rescale(). I took the values under -100 as outliers and change colour gradient under -100. It would be better to give nbin large value because the legend need to express rapid change at zero.
code :
library(ggplot2); library(scales)

  ## combine fill values (because of convenience, not necessary)
dat <- cbind(dat, ratio2 = as.numeric(sprintf("%1.2f", 100 * dat$ratio)))

  ## get max and min values using range(data)
r_range <- range(dat$ratio2, na.rm = T)

  ## defaine values and colours
   # values for heatmap
main_val <- c(r_range[1], seq(-100, -1.0E-6, length = 3),  # minus
              seq(1.0E-6, r_range[2], length = 3))         # plus

   # values for legend (I made two patterns; ignore outliers or not)
legend_val_100_max <- main_val[-1]
legend_val_120_max <- c(-120, seq(-100, -1.0E-6, length = 3),
                        seq(1.0E-6, r_range[2], length = 3))

   # colours    
mycol <- c("navy", "blue", "cyan", "lightcyan",              # minus
           "yellow", "red", "red4")                          # plus
g <- ggplot(data = dat, aes(x = ACC, y = variable)) +
  geom_tile(aes(fill = ratio2), colour = 'white') +
  theme(axis.text.x = element_text(angle = 60, hjust = 1, color="black"), 
        legend.title = element_blank(), legend.position="top", legend.key.size = unit(2.5, "cm")) + 
  scale_fill_gradientn(colours = mycol, values = rescale(main_val), guide = F)

  # to check
ggplot(data = dat, aes(x = ACC, y = variable)) +
  geom_tile(aes(fill = cut(ratio2, breaks = c(-Inf, 0, Inf))), colour = 'white')
  # -100 to max version (ignore outliers)
g + scale_colour_gradientn(colours = mycol[-1], values = rescale(legend_val_100_max),
                           limits = c(-100, max(dat$ratio2, na.rm=T)), breaks= c(-80, -40, 0, 40, 80),
                           guide = guide_colorbar(nbin=100))

  # -120 to max version (but chaged labels to look like min to max)
g + scale_colour_gradientn(colours = mycol, values = rescale(legend_val_120_max),
                         limits = c(-120, max(dat$ratio2, na.rm=T)), 
                         breaks = c(-120, -111, -109,  -100, -50, 0, 50),
                         labels = c(-500, "/", "/", -100, -50, 0, 50), #  (to be exact, not -500 but -494.42))
                         guide = guide_colorbar(nbin=100))
  # I used -200 as the limit to distinguish -151.30 from -494.42 (`sort(dat$ratio2, na.last = T)[1:2])`)
limited_val <- c(-200, seq(-100, -1.0E-6, length = 3),
                 seq(1.0E-6, r_range[2], length = 3))

ggplot(data = dat, aes(x = ACC, y = variable)) +
  geom_tile(aes(fill = ratio2), colour = 'white') +
  theme(axis.text.x = element_text(angle = 60, hjust = 1, color="black"), 
        legend.title = element_blank(), legend.position="top", legend.key.size = unit(2.5, "cm")) + 
  scale_fill_gradientn(colours = mycol, values = rescale(limited_val), 
                       limits = c(-200, max(dat$ratio2, na.rm=T)), breaks = c(-100, -50, 0, 50),
                       oob=squish, guide = guide_colorbar(nbin = 100))


Share : facebook icon twitter icon
ggplot2 heatmap, color scale with conditions

ggplot2 heatmap, color scale with conditions


By : Frank Peters
Date : March 29 2020, 07:55 AM
With these it helps I hope the code formatting is an artifact of the SO paste. I prefer more structured ggplot builds.
You can have far more control if you generate discrete breaks:
code :
library(ggplot2)
library(reshape2) 

tt <- data.frame(C1=c(0.4,.5,.5, 0, .8,.8),
                 C2=c(.5,.6,.7, 0, .7,.8), 
                 C3=c(.8,.7,.9, 0, .8,.7), 
                 C4=c(rep(0,6)), 
                 C5=c(0.4,.6,.6, 0, .8,.8),
                 C6=c(0.8,.7,.5, 0, .8,.8), 
                 C7=c(0.8,.6,.4, 0, .8,.8))

row.names(tt) <- paste("F", 1:6, sep='')
tt <- as.matrix(tt)

tt_melt <- melt(tt) 
colnames(tt_melt) <- c('fila', 'columna', 'performance')

tt_melt$cut <- cut(tt_melt$performance, 
                   breaks=c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0),
                   labels=as.character(c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)),
                   include.lowest=TRUE)

perf_cols <- c("white", colorRampPalette(c("red", "green"))( 9 ))
perf_text_cols <- c("black", rep("white", 9))

gg <- ggplot(data=tt_melt, aes(x=columna, y=fila, fill=cut))
gg <- gg + geom_tile()
gg <- gg + geom_text(aes(label=performance, color=cut)) 
gg <- gg + labs(title = 'Performance por posicion en el call')
gg <- gg + coord_equal()
gg <- gg + scale_colour_manual(values = perf_text_cols)
gg <- gg + scale_fill_manual(values=perf_cols)
gg <- gg + theme_minimal(base_size = 12, base_family = "")
gg <- gg + theme(legend.position="none")
gg
gg <- ggplot(data=tt_melt, aes(x=columna, y=fila, fill=cut))
gg <- gg + geom_tile()
gg <- gg + geom_text(aes(label=performance), color="white") 
gg <- gg + labs(title = 'Performance por posicion en el call')
gg <- gg + coord_equal()
gg <- gg + scale_fill_manual(values=perf_cols)
gg <- gg + theme_minimal(base_size = 12, base_family = "")
gg <- gg + theme(legend.position="none")
gg
How to create a heatmap with continuous scale using ggplot2 in R

How to create a heatmap with continuous scale using ggplot2 in R


By : Andrea Tovar
Date : March 29 2020, 07:55 AM
should help you out I have got a data frame with several 1000 rows in the form of , Does this help you?
code :
library(ggplot2)
group = c("gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr3","gr3","gr3","gr3","gr3","gr3","gr3","gr3","gr3","gr3")
pos = c(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10)
color = c(2,2,2,2,3,3,2,2,3,2,1,2,2,2,1,1,1,1,1,1,2,2,2,2,2,2,1,1,2,2)
df = data.frame(group, pos, color)
ggplot(data = df, aes(x = group, y = pos)) + geom_tile(aes(fill = color)) 
library(scales)
ggplot(data = df, aes(x = group, y = pos)) + geom_tile(aes(fill = color))+ scale_fill_gradientn(colours=c("orange","black","yellow"),values=rescale(c(1, 2, 3)),guide="colorbar")
R Heatmap: conditionally change label text colours with (ggplot2 or plotly)

R Heatmap: conditionally change label text colours with (ggplot2 or plotly)


By : saya qubit
Date : March 29 2020, 07:55 AM
it helps some times With ggplot2, you can use colour in the aes of geom_text (+ scale_colour_manual):
code :
ggplot(test_dat_numerics, aes(date, sig, fill = number_ok)) +
  geom_tile() +
  geom_text(aes(label = number_ok, colour =ifelse(number_ok>50, "black", "white"))) +
  scale_colour_manual(values=c("white"="white", "black"="black")) +
  theme(legend.position="none")
tweaking scale heatmap with ggplot2

tweaking scale heatmap with ggplot2


By : Steve Ball
Date : March 29 2020, 07:55 AM
This might help you I am a complete newbie with R and please forgive me if this already has been asked a gazillion times. I am trying to make a heatmap using R, following this example, which are tsvs. , By default we have ?rescale
Where are the scale colours stored in a ggplot2 object?

Where are the scale colours stored in a ggplot2 object?


By : Danish Sulaiman
Date : March 29 2020, 07:55 AM
should help you out Not much progress, but I've ruled out a few places that it might be hiding.
You can see all the character vector that p contains with
Related Posts Related Posts :
  • Extract single plot from ggplot with facet_grid
  • R: Subtract values from rows based on another column
  • Data Frame Transcode 1-0
  • Why can't we use . as a parameter in an anonymous function with %>%
  • How does R reference unassigned values?
  • How to interpret ACF plot y-axis scale in R
  • Naming resulting data.table columns after aggregation in R
  • can't write timestamps in PostgreSQL using RPostgres dbWriteTable
  • Why doesn't "mar" argument to plot.default get used?
  • How to extract dimension of a submatrix from a bigger matrix using R?
  • Area estimation using image in R
  • Building a symmetric binary matrix
  • Change color and add shape to lines on ggplot2 geom_freqpoly
  • Count event occurrence and assign it to individuals according to date and place of interview
  • ggplot2 is mutating/transforming size variables -- how to get back original data?
  • How to output literal backticks in knitr::spin
  • geom_text how to position the text on bar as I want?
  • How to escape the symbol of percentage '%' in r?
  • How to get R plot to plot variable on heat.color scale
  • Dynamically selecting principal components from the PCA output
  • Replicate a regression using a random subset of data each time and check distribution of regression coefficients?
  • How to find a string in a vector in r?
  • How to replace outliers with NA having a particular range of values in R?
  • rearrange data: convert from water year to calendar year
  • Plot multiple graphs on one plot in R within loop
  • Unconditional Probability Calculation in R
  • Calculate & add column length_of_time from date column in R
  • Asterisk in ggplot's annotate()
  • How to copy a row from a data frame to a matrix in R?
  • Importing a similar column (eg. pH column) from 60 csv files thru use of loop and making a matrix .
  • Reading text file with multi-char delimiter to a list in R
  • Looking to save a 3D spectrograph generated by SeeWave as .STL or similar in R
  • Separating three dimensional array by the stratifying variable
  • "Object '...' not found when referenced object is a nested function in R
  • How to correctly clearShapes in Leaflet in a Shiny app
  • NetLogo 5.3.1 and R 3.3.1 on Mac 10.10.6 headless exception
  • Extract unique values from column in dataframe, grouped by ID
  • Stacked Bar Chat (ggplot) in R:: Trying to create more than one bar in the chart
  • R: Creating a function to merge two columns
  • Error in knearest(Darr, P_set, K) : object 'knD' not found
  • Determining least significant predictor in Linear Regression Model with R
  • listcolumns and multidplyr
  • How to check for the presence of a location in a sentence in R?
  • Using mapply over a matrix when the function makes use of elemets' location in the matrix
  • R - stratified sampling for Person Period file
  • Merging two xts to create NAs at certain time stamps
  • How to subset data in a loop in R?
  • How to use sprintf to show string "\t"?
  • Subset Columns based on partial matching of column names in the same data frame
  • R Extract number from string
  • How to put 2 boxplot in one graph in R without additional libraries?
  • ggplot omits polygon holes
  • ggplot2 geom_boxplot side by side with facets
  • outlier labels incorrectly assigned with ggplot2 box plot
  • capture column pattern frequency
  • R remove tags starting with U
  • R, dplyr and snow: how to parallelize functions which use dplyr
  • R: Separate String Without Delimiter (like Fixed Width in Excel)
  • In R, is there a parsimonious or efficient way to get a regression prediction holding all covariates at their means?
  • Determine mode locations of the kernel density estimate of multimodal univariate data
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com