R ggplot图颜色渐变在两个不同的图中相同

时间:2020-09-13 08:28:47

标签: r ggplot2 plot viridis

您好,我正在使用ggplot绘制两个图表,以发送两个不同的数据,并使用viridis颜色渐变。由于数据的关系,两个图形的颜色梯度是不同的,所以我想使它相同,任何人都可以建议我

数据

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

编码我的使用

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 个答案:

答案 0 :(得分:2)

这可以通过在两个图中为色标设置相同的限制来实现。

使用mtcars作为示例数据集,请尝试以下操作:

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))

编辑:

对于您的数据,您可以使用例如

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

给出:

enter image description here