【问题标题】:Plotting line chart with different colours for pos and neg values为 pos 和 neg 值绘制不同颜色的折线图
【发布时间】:2019-05-05 01:11:40
【问题描述】:

我想为正负值绘制不同颜色的折线图。 不幸的是,绘图有些错误。 0 旁边的一些值以错误的颜色显示。

代码:

set.seed(345); df2 <- data.frame(date=1:100, y=cumsum(runif(100)-0.5))
d <- ggplot2::ggplot( df2, ggplot2::aes(date, y) ) +
   ggplot2::geom_line( ggplot2::aes( group = 1, color= (y < 0)));d

任何想法为什么绘图不起作用?

【问题讨论】:

  • 这里的颜色是根据每个段开头的值来的。要为所有负值和正值获得不同的颜色,您需要对数据进行插值以在每个交叉点都有一个点。
  • 使用approx 进行插值

标签: r ggplot2


【解决方案1】:

geom_line() 将使用当前点的值从当前点到下一个点着色。我希望这张图表有助于解释:

set.seed(345)

df2 <- 
  data.frame(
    date = 1:100, 
    y = cumsum(runif(100) - 0.5)
  ) %>% 
  mutate(line_color = y < 0) 

ggplot(slice(df2, 60:85), aes(date, y, color = line_color)) +
  geom_segment(
    aes(
      x = (date), xend = lead(date), 
      y = (y), yend = lead(y)
    ), 
    arrow = arrow(length = unit(0.15, "inches"), ends = "first"),
    size = 1
  ) +
  geom_point(size = 3) +
  geom_hline(yintercept = 0)

您可以使用lead()lag() 逻辑来提前确定您想要的颜色。此示例将为值

df2 %>% 
mutate(line_color =  y < 0 | lead(y, default = first(y)) < 0) %>%
ggplot(aes(date, y, color = line_color)) +
  geom_line(aes(group = 1)) +
  geom_point(aes(color = y < 0), size = 3) +
  geom_hline(yintercept = 0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多