簡體   English   中英

將ggplot色階漸變應用於部分數據

[英]apply ggplot color scale gradient to portion of data

我對應用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或與data(100),y,x相同”。 我知道發生這種情況是因為負數數據的長度與整個數據集的長度不同,但是我想不出辦法。 任何建議將不勝感激。

謝謝柯蒂斯

您需要對數據進行子集化,並使用geom_bar fill aes()

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

在此處輸入圖片說明

希望這就是您想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM