如何在ggplot中增加hexbin图例

时间:2019-08-23 11:02:14

标签: r ggplot2

我有以下六边形图:

enter image description here

我希望计数从最低计数(例如10)开始,并用不同的颜色显示。请注意,最低计数随不同的数据集而有所不同。因此,很难将其设置为特定数字。我编写的用于生成绘图的脚本是:

d <- ggplot(selectedDF, aes(BEC_Agg, AC)) + geom_hex(bins = 30) + theme_bw() +
    theme(text = element_text(face = "bold", size = 16)) + xlab("\nNormalized BEC") + ylab("AC\n")  + scale_fill_gradientn(colors = brewer.pal(3,"Dark2"))

我尝试了解决方法here

d <- ggplot(selectedDF, aes(BEC_Agg, AC)) + geom_hex(aes(fill=cut(..value..,breaks=pretty(..value..,n=5))),bins = 30) + theme_bw() +
    theme(text = element_text(face = "bold", size = 16)) + xlab("\nNormalized BEC") + ylab("AC\n")  + scale_fill_gradientn(colors = brewer.pal(3,"Dark2"))

但是我遇到了以下错误:

Error in cut(value, breaks = pretty(value, n = 5)) : 
  object 'value' not found

我该如何解决?

2 个答案:

答案 0 :(得分:0)

您应该在运行ggplot之前定义变量value。由于最低计数在数据集中有所不同,因此您可能需要尝试类似value <- min(count(yourDF))的方法。

答案 1 :(得分:0)

由于您的重点是调整图例,因此这是一种方法。您未提供任何示例数据。

# sample dataframe 
set.seed(77)
x=rnorm(1000, mean = 4, sd = 1)
y=rnorm(1000, mean = 2, sd = 0.5)
df <- data.frame(x,y)
# -------------------------------------------------------------------------
# The following is from your script
base <- ggplot(df, aes(x, y)) + geom_hex(bins = 30) + theme_bw() +
  theme(text = element_text(face = "bold", size = 16)) + xlab("\nNormalized BEC") + ylab("AC\n") 
# -------------------------------------------------------------------------
base_limit_break <- base + scale_fill_continuous(limits = c(1,20), breaks = c(1:20))
# -------------------------------------------------------------------------
# This is the part relevant to your question 
base_limit_break + guides(fill = guide_colorbar(barheight = unit(10, "cm"), reverse = TRUE))

输出

tweak_legend

相关问题