如何从qicharts2包中获得基于ggplot2的图表?

时间:2018-03-23 17:06:56

标签: r ggplot2

qicharts2 是一个统计过程控制包,用于绘制控制图。让我们绘制一个示例图表:

library(qicharts2)
library(ggplot2)

(plot1 <- qic(age,
  data    = tail(cabg, 100), 
  chart   = 'i',
  exclude = c(45, 70),
  title   = 'Age of the last 100 patients (I chart)',
  ylab    = 'Years',
  xlab    = 'Patient #')
  )
p1 <- plot1$data

我可以自定义此图表,从中提取数据plot1$data并执行典型的ggplot2自定义。见下文。

(plot2 <- ggplot(plot1$data, aes(x,y)) +
  geom_ribbon(ymin = p1$lcl, ymax = p1$ucl, fill = "green", alpha = 0.4) +
  geom_line(colour = "blue", size = .75) + 
  geom_line(aes(x, cl)) +
  geom_point(colour = "black" , fill = "black", size = 1.5) +
  ggtitle(label = "example i chart") +
  labs(x = NULL,
       y = NULL)+
  theme_minimal()
  )

让我们继续按性别划分情节1,我们称之为情节3。

(plot3 <- qic(age,
  data    = tail(cabg, 100), 
  chart   = 'i',
  exclude = c(45, 70),
  title   = 'Age of the last 100 patients (I chart)',
  ylab    = 'Years',
  xlab    = 'Patient #', 
  facet   = ~ gender)
)
p3 <- plot3$data

我想创建一个使用与plot 4相同的选项的plot 2,但其面向plot 3。我需要在第二部分代码中添加什么才能使其按性别划分?

1 个答案:

答案 0 :(得分:2)

您要查找的facet存储在plot3$data$facet1

library(qicharts2)
library(ggplot2)

plot3 <- qic(age,
             data    = tail(cabg, 100),
             chart   = 'i',
             exclude = c(45, 70),
             title   = 'Age of the last 100 patients (I chart)',
             ylab    = 'Years',
             xlab    = 'Patient #',
             facet   = ~ gender)

p3 <- plot3$data

plot4 <- ggplot(p3, aes(x,y)) +
  geom_ribbon(ymin = lcl, ymax = ucl, fill = "green", alpha = 0.4) +
  geom_line(colour = "blue", size = .75) + 
  geom_line(aes(x, cl)) +
  geom_point(colour = "black" , fill = "black", size = 1.5) +
  ggtitle(label = "example i chart") +
  labs(x = NULL,
       y = NULL)+
  theme_minimal() +
  facet_grid(~ facet1)
plot4

reprex package(v0.2.0)创建于2018-03-23。