将ggplot颜色比例渐变应用于数据的一部分

时间:2017-11-20 18:04:25

标签: r ggplot2 color-scheme

我对应用ggplot的色阶渐变有疑问。我有数据集,其中响应变量是一个连续变量,包括正数和负数,而自变量是一些独立的站点。我试图以这样的方式绘制数据:我可以在背景中绘制所有数据,然后将颜色比例梯度应用于覆盖数据负范围的响应数据。这是我到目前为止所拥有的一个模拟我的实际数据集结构的示例数据集。

 tr_sim <- data.frame(site_id = seq(1,100,1), estimated_impact = 
    rnorm(100,18,200), impact_group = rep(c(1,2),each = 50))

    rng_full <- range(tr_sim$estimated_impact)
    #produce plot showing the full range of impacts across all sites and then 
    over the subsetted sites

    impact_plot_full <- ggplot(data = tr_sim, aes(x = factor(site_id, levels = 
    site_id[order(estimated_impact)]), y = estimated_impact)) +
    geom_bar(stat = "identity",width = 1, fill = "grey80") 

    impact_plot_full 

    impact_plot_full + 
   geom_bar(stat = "identity", width = 1, position = "stack", aes(y  = 
   estimated_impact[impact_group == 1])) +
  scale_fill_gradient2(low="firebrick", mid="yellow", high = "green4") +
  labs(y = "Estimated Impact ($/week)", x = "Total number of sites with estimate 
  is 100", title = "Sites with the greatest impact after coverage loss") +
  theme(axis.text.x = element_blank()) +
  scale_y_continuous(breaks = 
  round(seq(rng_full[1],rng_full[2],by=100),digits=0)) 

我可以将背景中的所有数据绘制为灰色,并且我试图在此基础上绘制响应数据的负范围。我得到的错误是'美学必须是长度1或与数据(100),y,x'相同。我知道这是因为负数据与整个数据集的长度不同,但我无法找到一种方法。任何建议都将不胜感激。

谢谢你, 柯蒂斯

1 个答案:

答案 0 :(得分:0)

您需要对数据进行分组,并在fill aes()中使用geom_bar

impact_plot_full + 
geom_bar(data = subset(tr_sim, estimated_impact < 0), 
         stat = "identity",
         aes(y = estimated_impact, fill = estimated_impact)) + 
scale_fill_gradient2(low = "firebrick", mid = "yellow", high = 
"green4") +
theme(axis.text.x = element_blank()) +
xlab("site_id")

enter image description here

希望这是你正在寻找的。

相关问题