我有以下代码:

install.packages("tidyverse")
library("tidyverse")
data(diamonds)

ggplot(data=diamonds)+
  geom_point(mapping=aes(x=carat,y=price),color="blue")+
  geom_hline(aes(yintercept=max(price)),
             color="seagreen")+
  annotate("text",x=3.5,y=19600,label=
           scales::comma(max(diamonds$price),
                        accuracy=1),
                 size=5,color="seagreen",
           fontface="bold.italic")+
  facet_wrap(facets = "cut")

My current result is shown as the graphic below: enter image description here I want to facet each "cut" level, and show the prices against carats. With the geom_hline, I want to show the highest price in each facet. However, I do not know how to do it.

我试着查找类似的问题,发现了这篇帖子: Different `geom_hline()` for each facet of ggplot

这个问题与我的类似,但我不知道如何遵循建议的解决方案:如何将每个方面划分为不同的列?有没有办法在不修改原始数据库的情况下做到这一点?

谢谢大家

推荐答案

您可以通过为每cut个数据框创建最高价格的新数据框来实现这一点

library(tidyverse)

max_prices <- diamonds %>%
  group_by(cut) %>%
  summarise(yintercept = max(price))

ggplot(data = diamonds) +
  geom_point(mapping = aes(x = carat, y = price), color = "blue") +
  geom_hline(data = max_prices, aes(yintercept = yintercept), color = "seagreen") +
  geom_text(data = max_prices, mapping = aes(x = 3.5, y = 19600, label = scales::comma(yintercept, accuracy = 1)), 
            size = 5, color = "seagreen", fontface = "bold.italic") +
  facet_wrap(facets = "cut")

创建于2023-08-08,共reprex v2.0.2

R相关问答推荐

如果索引重复,聚合xts核心数据

terra nearest()仅为所有`to_id`列返回NA

如何删除gggvenn与gggplot绘制的空白?

如何将dygraph调用到R Markdown作为一个shiny 的react 对象的参数?

r替换lme S4对象的字符串的一部分

derrr mutate case_when grepl不能在R中正确返回值

如何在Chart_Series()中更改轴值的 colored颜色 ?

为什么当用osmdata映射R时会得到相邻状态?

使用rest从header(h2,h3,table)提取分层信息

计算直线上点到参考点的总距离

来自程序包AFEX和amp;的类/函数和NICE_TABLE&冲突

如何移除GGPlot中超出与面相交的任何格网像元

我是否可以使用多个变异项来构建顺序列(标记多个问题)

如何在AER::ivreg中指定仪器?

抽样变换-REXP与RWEIBUR

具有自定义仓位限制和计数的GGPLATE直方图

GOGPLATE geom_boxploy色彩疯狂

以R表示的NaN值的IS.NA状态

通过比较来自多个数据框的值和R中的条件来添加新列

R dplyr::带有名称注入(LHS of:=)的函数,稍后在:=的RHS上引用