R ggplot graph color gradient same for two different plots

1k views Asked by At

Hello I am ploting two graph using ggplot for two different data sent and using viridis colour gradient. because of data two graph colour gradient are different so I wanted make it same can any one suggest me

data

https://drive.google.com/file/d/1HUbEQMjIS3ybYuKUaVXT9M_f4ZR-BQXt/view?usp=sharing

code what i used

library("viridis") 

df=read.table("test.txt",sep='\t', header=TRUE)
df = data.frame(df)

#first data
df$log_mean=log(df$data1)
df$data3=log2(df$data3)
df$data2=log2(df$data2)
#second data
df$log_mean2=log(df$df1)
df$df3=log2(df$df3)
df$df2=log2(df$df2)


#plot1
p1=ggplot(df, aes(data3,data2),pch=19,cex=1.9)+
  geom_point(aes(color =log_mean)) +
  theme(legend.position = "top")+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  theme(text = element_text(size = 20, face="bold"))

#plot2
p2=ggplot(df, aes(df3,df2),pch=19,cex=1.9)+
  geom_point(aes(color =log_mean2)) +
  theme(legend.position = "top")+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  theme(text = element_text(size = 20, face="bold"))

#viridis color
p1+scale_color_viridis(option = "C")
p2+scale_color_viridis(option = "C")
1

There are 1 answers

4
stefan On BEST ANSWER

This could be achieved by setting the same limits for the color scale in both plots.

Using mtcars as example dataset try this:

library(ggplot2)
library(dplyr)

mtcars1 <- filter(mtcars, cyl == 4)
mtcars2 <- filter(mtcars, cyl == 6)

p1 <- ggplot(mtcars1, aes(hp, mpg, color = mpg)) +
  geom_point()

p2 <- ggplot(mtcars2, aes(hp, mpg, color = mpg)) +
  geom_point()

p1 + scale_color_viridis_c(limits = c(18, 33))

p2 + scale_color_viridis_c(limits = c(18, 33))

Edit:

For your data you can use e.g.

p1 + scale_color_viridis(option = "C", limits = c(-1, 8))
p2 + scale_color_viridis(option = "C", limits = c(-1, 8))

which gives:

enter image description here