これは私が最近尋ねた質問の続きです(Manually assigning colors with scale_fill_manual only works for certain hexagon sizes)。色の手動割り当てのための六角形と凡例の一致
すべての六角形が同じサイズになるようにgeom_hex()をプロットできませんでした。誰かが問題を解決しました。しかし、その解決策は凡例キーを削除しました。今、六角形をすべて同じサイズに保つことができず、凡例も保持できません。
具体的には、私は本当に伝説のラベルをセンセーショナルにしたいと思っています。以下の例では、凡例は16進数のラベル(#08306B、#08519Cなど)ではなく、値(0,2,4,6,8,20)を持っています。
以下は、問題を示すMWEです。最後に、3つのコメントごとに、私は1)六角形のサイズは統一されているが凡例は作成されていないこと、2)凡例は一貫しない六角形のプロットを作成できること、3)一貫性のある六角サイズや伝説を持つプロットが、失敗:伝説を維持しながら、一貫性のあるサイズの六角形を維持する方法について
library(ggplot2)
library(hexbin)
library(RColorBrewer)
library(reshape)
set.seed(1)
xbins <- 10
x <- abs(rnorm(10000))
y <- abs(rnorm(10000))
minVal <- min(x, y)
maxVal <- max(x, y)
maxRange <- c(minVal, maxVal)
buffer <- (maxRange[2] - maxRange[1])/(xbins/2)
bindata = data.frame(x=x,y=y,factor=as.factor(1))
h <- hexbin(bindata, xbins = xbins, IDs = TRUE, xbnds = maxRange, ybnds = maxRange)
counts <- hexTapply (h, bindata$factor, table)
counts <- t (simplify2array (counts))
counts <- melt (counts)
colnames (counts) <- c ("factor", "ID", "counts")
counts$factor =as.factor(counts$factor)
hexdf <- data.frame (hcell2xy (h), ID = [email protected])
hexdf <- merge (counts, hexdf)
my_breaks <- c(2, 4, 6, 8, 20, 1000)
clrs <- brewer.pal(length(my_breaks) + 3, "Blues")
clrs <- clrs[3:length(clrs)]
hexdf$countColor <- cut(hexdf$counts, breaks = c(0, my_breaks, Inf), labels = rev(clrs))
# Has consistent hexagon sizes, but no legend
ggplot(hexdf, aes(x=x, y=y, hexID=ID, counts=counts, fill=countColor)) + geom_hex(stat="identity", fill=hexdf$countColor) + scale_fill_manual(labels = as.character(c(0, my_breaks)), values = rev(clrs), name = "Count") + geom_abline(intercept = 0, color = "red", size = 0.25) + labs(x = "A", y = "C") + coord_fixed(xlim = c(-0.5, (maxRange[2]+buffer)), ylim = c(-0.5, (maxRange[2]+buffer))) + theme(aspect.ratio=1)
# Has legend, but inconsistent hexagon sizes
ggplot(hexdf, aes(x=x, y=y, hexID=ID, counts=counts, fill=countColor)) + geom_hex(data=hexdf, stat="identity", aes(fill=countColor)) + scale_fill_manual(labels = as.character(c(0, my_breaks)), values = rev(clrs), name = "Count") + geom_abline(intercept = 0, color = "red", size = 0.25) + labs(x = "A", y = "C") + coord_fixed(xlim = c(-0.5, (maxRange[2]+buffer)), ylim = c(-0.5, (maxRange[2]+buffer))) + theme(aspect.ratio=1)
# One attempt to create consistent hexagon sizes and retain legend
ggplot(hexdf, aes(x=x, y=y, hexID=ID, counts=counts, fill=countColor)) + geom_hex(data=hexdf, aes(fill=countColor)) + geom_hex(stat="identity", fill=hexdf$countColor) + scale_fill_manual(labels = as.character(c(0, my_breaks)), values = rev(clrs), name = "Count") + geom_abline(intercept = 0, color = "red", size = 0.25) + labs(x = "A", y = "C") + coord_fixed(xlim = c(-0.5, (maxRange[2]+buffer)), ylim = c(-0.5, (maxRange[2]+buffer))) + theme(aspect.ratio=1)
任意の提案は非常に参考になります!
幻想的で詳細なソリューションをありがとう!はい、あなたは正しいです。私は実際に連続性を示すために伝説のラベルを変更しています。この場合、all_break_labsは実際には "0-2"、 "2-4"、 "4-6"、 "6-8"、 "8-20"、 "20+" –