【问题标题】:Colour the most expensive and least expensive observations in R为 R 中最昂贵和最便宜的观察结果着色
【发布时间】:2020-08-13 10:02:37
【问题描述】:

所以我有一个包含 168 个观察值的每小时价格序列,我的目标是将它们绘制在图表中,其中 x 轴上的小时数从 1-168 编号,y 轴上的价格。我的问题是我想将 20 个最昂贵的小时标为红色,将 40 个最便宜的小时标为绿色,其余的应该标为蓝色。这是我目前所拥有的。


DF <- read_excel("Downloads/Copy of ee_2020-08-10_ExpV.xls", 
                                        col_types = c("date", "text"))

colnames(DF) <- c("Date", "Prices")
DF <- DF[-1,]

# Convert FB to tbl_time
DF <- as_tbl_time(DF, index = Date)

DF <- filter_time(DF, time_formula = '2020-09-21' ~ '2020-09-27')


【问题讨论】:

  • 您需要提供一个可重现的示例。我需要能够运行你的代码,否则真的很难帮你。
  • 在你 read_excel() 之后,使用 dput(DF)。将内容粘贴到问题中,以便我们运行您的代码并尝试一些事情。

标签: r dplyr


【解决方案1】:

没有示例数据,很难重现您的情况并提供适当的答案。但是,这里有一个示例,说明如何通过有条件地为数据分配一个因子来实现它。

library(dplyr)
library(ggplot2)

df <- data.frame(price = runif(168)*10, hours = 1:168) # Make the dataframe
df <- df %>% mutate(colfac = ifelse(price > sort(price,decreasing = TRUE)[21],1,0)) # Assign 1 to top 20 prices
df <- df %>% mutate(colfac = ifelse(price < sort(price,decreasing = TRUE)[168-40],2,colfac)) # Assign 2 to bottom 40, and 3 to everything else

ggplot(data = df, aes(x = hours, y = price, col = as.factor(colfac))) +
  geom_point()

reprex package (v0.3.0) 于 2020-08-13 创建

【讨论】:

    猜你喜欢
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多