-->

GGPLOT2多个stat_binhex()具有不同的颜色渐变绘制在一个图像(ggplot2 mul

2019-07-03 11:35发布

我想使用GGPLOT2的stat_binhex()使用scale_colour_gradientn同时绘制在同一张图上两个自变量,每个都有自己的颜色渐变()。

如果我们忽略一个事实,即在x轴的单位不匹配,可重复的例子是绘制以下在相同的图像,同时保持独立的填充渐变。

d <- ggplot(diamonds, aes(x=carat,y=price))+
  stat_binhex(colour="white",na.rm=TRUE)+
  scale_fill_gradientn(colours=c("white","blue"),name = "Frequency",na.value=NA)
try(ggsave(plot=d,filename=<some file>,height=6,width=8))

d <- ggplot(diamonds, aes(x=depth,y=price))+
  stat_binhex(colour="white",na.rm=TRUE)+
  scale_fill_gradientn(colours=c("yellow","black"),name = "Frequency",na.value=NA)
try(ggsave(plot=d,filename=<some other file>,height=6,width=8))

我发现在谷歌GGPLOT2组相关问题的一些谈话这里 。

Answer 1:

这里是另一个可能的解决方案:我已@ MNEL的映射斌的想法算到Alpha透明度,我已经改变了X变量,使他们能够在同一坐标绘制。

library(ggplot2)

# Transforms range of data to 0, 1. 
rangeTransform = function(x) (x - min(x)) / (max(x) - min(x))

dat = diamonds
dat$norm_carat = rangeTransform(dat$carat)
dat$norm_depth = rangeTransform(dat$depth)

p1 = ggplot(data=dat) +
     theme_bw() +
     stat_binhex(aes(x=norm_carat, y=price, alpha=..count..), fill="#002BFF") +
     stat_binhex(aes(x=norm_depth, y=price, alpha=..count..), fill="#FFD500") +
     guides(fill=FALSE, alpha=FALSE) +
     xlab("Range Transformed Units")

ggsave(plot=p1, filename="plot_1.png", height=5, width=5)

思考:

  1. 我试图(和失败的),以显示一个合理的颜色/ alpha图例。 似乎棘手,但应该可以给所有GGPLOT2传说中的定制功能。

  2. X轴单元标记需要一些种溶液。 绘制两套单元上有一个轴由许多令人难以接受的,并具有GGPLOT2没有这样的功能。

  3. 重叠颜色细胞的解释似乎在这个例子不够清晰,但可以根据所使用的数据集,和所选择的颜色变得非常混乱。

  4. 如果两种颜色添加剂的补充,那么无论他们同样重叠,你会看到一个中性灰色。 其中的重叠不等,灰色将转向更黄,或更蓝。 我的颜色不相当互补,由灰色重叠细胞的略微粉红色调判断。



Answer 2:

我想你想要什么违背原则ggplot2和图形的语法更接近一般。 直到问题被解决(对此我不会认为我的呼吸),你有几种选择

使用facet_wrapalpha

这是不会交出了漂亮的传说,但需要你好歹给你想要的东西。

您可以设置alpha的计算值按比例Frequency ,通过访问..Frequency..

我不认为你可以很好地虽然合并的传说。

library(reshape2)
# in long format
dm <- melt(diamonds, measure.var = c('depth','carat'))

ggplot(dm, aes(y = price, fill = variable, x = value)) + 
   facet_wrap(~variable, ncol = 1, scales  = 'free_x') + 
   stat_binhex(aes(alpha = ..count..), colour = 'grey80') + 
    scale_alpha(name = 'Frequency', range = c(0,1)) + 
    theme_bw() + 
    scale_fill_manual('Variable', values = setNames(c('darkblue','yellow4'), c('depth','carat')))

使用gridExtragrid.arrangearrangeGrob

您可以创建单独的图形和使用gridExtra::grid.arrange单个图像上安排。

d_carat <- ggplot(diamonds, aes(x=carat,y=price))+
  stat_binhex(colour="white",na.rm=TRUE)+
  scale_fill_gradientn(colours=c("white","blue"),name = "Frequency",na.value=NA)

d_depth <- ggplot(diamonds, aes(x=depth,y=price))+
  stat_binhex(colour="white",na.rm=TRUE)+
  scale_fill_gradientn(colours=c("yellow","black"),name = "Frequency",na.value=NA)

library(gridExtra)


grid.arrange(d_carat, d_depth, ncol =1)

如果你想这与工作ggsave (感谢@bdemarest下方@baptiste评论)

更换grid.arrangearrangeGrob类似。

ggsave(plot=arrangeGrob(d_carat, d_depth, ncol=1), filename="plot_2.pdf", height=12, width=8)


文章来源: ggplot2 multiple stat_binhex() plots with different color gradients in one image