用带状图绘制线图的背景

时间:2015-02-17 17:41:02

标签: r plot ggvis

[编辑标题并删除了主要问题的次要问题]

我想要的是一个带点(简单)的简单线条图,其背景由层级数据框架创建(对我来说很难)

我正在尝试重新创建的示例 example plot CODE

# libraries used  
library(dplyr)  
library(ggvis)  
library(magrittr)  

# create example data frame
months <- c("oct", "nov", "dec", "jan", "feb", "march", "april", "may",
"june")
#months <- 1:9
tier3low <- (rep(150, 9))
tier3high <- c(157, 158, 162, 162, 166, 167, 169, 172, 172)
tier2high <- c(164, 166, 170, 171, 176, 178, 180, 182, 182)
tier1high <- rep(185, 9)
tier_range <- seq(from = 150, to = 185, by = 4)
scores <- c(156, 163, 162, 172, 173, 174, 175, 177, 183)
df <- data.frame(months, tier3low , tier3high, tier2high, tier1high,
tier_range, scores)
# make levels
levels(df$months) <- c("oct", "nov", "dec", "jan", "feb", "march", "april",
"may", "june")

# what I have tried
df %>%
  group_by(months) %>% 
  ggvis(x = ~months, y = ~tier_range) %>%
  layer_ribbons(y = ~tier3low,  y2 = ~tier3high, stroke := "red") %>% 
  layer_ribbons(y = ~tier3high, y2 = ~tier2high, stroke := "yellow") %>% 
  layer_ribbons(y = ~tier2high, y2 = ~tier1high, stroke := "green") %>% 
  layer_lines(y   = ~scores) %>% 
  layer_points(y  = ~scores)   

产生这个 enter image description here

根据评论请求编辑出这些问题  这些地块没有相互填充  2.实际线条未打印在图表上  3.数据已在错误的月份重新排列

主要问题

情节之间没有相互填充,我不明白为什么这不是正确的解决方案。你认为什么是更好的方法来实现这一目标。

1 个答案:

答案 0 :(得分:1)

你实际上并不遥远。你需要解决三件事:

您需要使用填充而不是笔划来确定色带的颜色

数据框需要按月分类,因为功能区从左到右绘制

你在ggvis的第一次调用中有一个y的剩余定义,我觉得很困惑,因为你必须在每一层中再次单独定义y(可能不会对你造成伤害,但肯定会让我感到困惑)。

以下是我认为您需要的内容:

df %>%
   arrange(months) %>%
   ggvis(x = ~months) %>%
   layer_ribbons(y = ~tier3low,  y2 = ~tier3high, fill := "red") %>% 
   layer_ribbons(y = ~tier3high, y2 = ~tier2high, fill := "yellow") %>% 
   layer_ribbons(y = ~tier2high, y2 = ~tier1high, fill := "green") %>% 
   layer_lines(y   = ~scores) %>% 
   layer_points(y  = ~scores)   

enter image description here