当临界水平以上时,geom_area填充颜色不同 [英] geom_area different fill colour when above critical level

查看:742
本文介绍了当临界水平以上时,geom_area填充颜色不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,如果我们有一个geom_area,其最大X值为50,我希望填充颜色在10以下时为蓝色,在10以上时为红色。

示例数据;

  df < -  data.frame(
y = sample(1:50),
x = sample(1:50)

到目前为止我设法得到的最接近的是使用下面的代码;

  ggplot(data = df,aes(x = x))+ 
geom_area(aes(y = y),fill =red )+
geom_ribbon(aes(ymin = 0,ymax = ifelse(y> = 10,10,y)),fill =blue)

这几乎让我满足了我的要求,然而问题在于水平分割不是完全跨过geom_area,因为当下一个值低于最大值时功能区直接进入下一个点,这会破坏分割。





这是精确地绘制代码告诉它的内容,所以我必须使用错误的方法来创建颜色分割,但无法弄清楚如何正确执行。 解决方案


I am trying to get a geom_area to have twin colours dependant on value of Y axis.

So for example if we have a geom_area with a max X value of 50, I would like the fill colour to be blue when below 10 and red when above 10.

Sample Data;

df <- data.frame(
  y = sample(1:50),
  x = sample(1:50)
)

The closest that I have managed to get thus far is by using the following code;

ggplot(data = df, aes(x = x)) + 
  geom_area(aes(y = y),fill = "red") +
  geom_ribbon(aes(ymin = 0, ymax = ifelse(y >= 10,10,y)),fill = "blue")

This almost gets me what I require however the problem is that the horizontal split is not completely across the geom_area, as when the next value falls below the max value the edge of the ribbon goes straight to the next point, which upsets the split.

This is plotting exactly what the code tells it, so I must be using the wrong method to create the split in colours, but cannot figure out how to do it correctly.

解决方案

A quick fix would be to interpolate between the x-values using approx. Set the n argument (the number of interpolation points) to a high-enough value to get blue all the way across:

ggplot(data = as.data.frame(approx(df,n=1000)), aes(x = x)) + 
  geom_area(aes(y = y),fill = "red") +
  geom_ribbon(aes(ymin = 0, ymax = ifelse(y >= 10,10,y)),fill = "blue") +
  theme_classic()

这篇关于当临界水平以上时,geom_area填充颜色不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆