简体   繁体   English

将ggplot色阶渐变应用于部分数据

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

I have a question about applying ggplot's color scale gradient. 我对应用ggplot的色阶渐变有疑问。 I have dataset where the response variable is a continuous variable including both positive and negative numbers, and the independent variable is a number of independent sites. 我有一个数据集,其中响应变量是包括正数和负数的连续变量,而自变量是多个独立站点。 I'm trying to plot the data in such a way that I can plot all of the data in the background and then apply a color scale gradient to response data that covers the negative range of the data. 我试图以一种可以在背景中绘制所有数据的方式绘制数据,然后将色阶渐变应用于覆盖数据负范围的响应数据。 This is what I have so far with a example dataset that mimics the structure of my actual dataset. 到目前为止,这是我的示例数据集,它模仿了我的实际数据集的结构。

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

I can plot all of the data in the background in gray and I'm attempting to plot the negative range of the response data on top of this. 我可以将背景中的所有数据绘制成灰色,并尝试在此之上绘制响应数据的负范围。 I get the error that 'aesthetics must be either length 1 or the same as the data(100), y,x'. 我得到一个错误,即“美学必须为1或与data(100),y,x相同”。 I know this is occurring because the negative data is not the same length as the entire dataset, but I can not figure out a way to do this. 我知道发生这种情况是因为负数数据的长度与整个数据集的长度不同,但是我想不出办法。 Any suggestions would be greatly appreciated. 任何建议将不胜感激。

Thank you, Curtis 谢谢柯蒂斯

You need to subset the data and use fill in the aes() for geom_bar . 您需要对数据进行子集化,并使用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")

在此处输入图片说明

Hope this is what You are looking for. 希望这就是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM