【问题标题】:How to fill out an area of a graph with ggplot2如何使用ggplot2填充图形的区域
【发布时间】:2021-07-24 21:25:23
【问题描述】:

我正在为我的一门经济学课程使用 R 绘制图表,我想填写图表的一个区域来表示无谓损失。

以下是我用来制作图表的代码:

rm(list = ls())
library(tidyverse)

housing_market <- ggplot(data.frame(x = c(0,3000)), aes(x = x)) +
  stat_function(fun = function(x){2.5-0.001*x}, color = "green", lwd = 1) +
  stat_function(fun = function(x){1}, color = "purple", lwd = 1) +
  stat_function(fun = function(x){0.70}, color = "blue", lwd = 1) +
  ylim(0,2.5) +
  annotate(geom = "text", label = "Inverse Demand = 2.5 - 0.001Q", x = 1250, y = 2, size = 4) +
  annotate(geom = "text", label = "MSC = 1", x = 500, y = 1.2, size = 4) +
  annotate(geom = "text", label = "MPC = 0.70", x = 500, y = 0.5, size = 4) +
  ggtitle("Housing Market") +
  labs(x = bquote(Q(ft.^2)), y = bquote(P("$"/ft.^2))) +
  geom_point(aes(1500,1), color = "black", size = 4) +
  geom_point(aes(1800,1), color = "black", size = 4) +
  geom_point(aes(1800,0.7), color = "black", size = 4)
housing_market

无谓损失是由点 (1500,1)、(1800,1) 和 (1800,0.7) 创建的三角形。我试过使用geom_rect,但我想不出一种方法让它只填充三角形。任何帮助将不胜感激。

【问题讨论】:

    标签: r ggplot2 economics


    【解决方案1】:

    显然,三角形是一个特定的多边形(而不是矩形);)

    您可以使用坐标定义数据框。我在 geom 调用中执行此操作。但是,从编码的角度来看,您可能希望在外部执行此操作。附带说明:您也可以使用此外部数据框来定义一个 geom_point() 调用中的点。

    housing_market + 
       geom_polygon(data = data.frame(  x = c(1500, 1800, 1800)
                                      , y = c(1,1,0.7))
                   , aes(x = x, y = y)   # set aesthetic mapping for polygon
                   , fill = "orange"     # put any other parameter
       )
    

    在最后添加 geom_polygon 图层将“覆盖”您的点。 因此,您可能希望在构建绘图时将geom_polygon() 层向上移动,或者在多边形调用之后放置geom_point() 调用。

    【讨论】:

    • 非常感谢Ray,就是这样!我也感谢你容忍我对 R 的绿色态度,正如我尝试使用 geom_rect 制作三角形时所展示的那样;)
    • 嗨,克里斯,没问题。相信我……白发的数量与吸取的教训成正比(我有……)。很高兴看到您畅通无阻并继续前进。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多