设置ggplot facet_wrap的数据

时间:2018-11-01 18:29:44

标签: r ggplot2 facet-wrap

数据:

enter image description here

我想做的是使用facet_wrap四个段,其中每个段包含三个图,x轴标记为Month-Year,y轴标记值,并且段1中的三个图将为L1 ,DRP-L1和OSM-L1等。

每个段的顶部标签为L1,L2,L3和L4。我的问题是,是否可以使用上面显示的数据进行设置,还是必须创建另一个标记为“位置”的列,该列将列出L1,L2,L3,L4,并且每行为每个位置提供一个值?

这是我到目前为止生成的代码,但是(1)我不确定如何在每个段中添加其他行,即DRP_1,OSM_1等;并且,(2)我不确定为什么不绘制零值?

library(ggplot2,scales)
month=rep(c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),4)
numparts=c(0,   0,  0,  0,  0,  0,  52000,  2000,   0,  0,  0,  0,
           0,   0,  0,  0,  35000,  5000,   0,  20000,  0,  0,  0,  0,
           0,   0,  7500,   17000,  625,    0,  50, 0,  0,  2500,   0,  0,
           0,   0,  250,    0,  1800,   900,    800,    500,    600,    0,  0,  11390)
location=c("Location 1","Location 2","Location 3","Location 4")
data=data.frame(month,numparts,location)

# Faceting
ggplot(data, aes(y=numparts, x=month)) + 
  geom_line( stat="identity") + 
  expand_limits(y=0)+
  scale_x_discrete(labels = month)+
  facet_wrap(~location,scales="free_y")+
  labs(x="Month in 2017",y="Number of Parts")

enter image description here

1 个答案:

答案 0 :(得分:1)

您的数据代码与屏幕截图中的代码不匹配。

这是示例数据,它从屏幕快照中提取了前5行:

要添加其他行,您需要组aes。看看this帖子。

library(ggplot2)
library(scales)

val <- c(0, 0, 0, 0, 0,
       0, 0, 0, 0, 35000,
       0, 0, 7500, 17000, 625, 
       0, 0, 250, 0, 1800,
       1548, 500, 0, 0, 0,
       430, 2857, 0, 0, 0,
       0, 0, 0, 0, 0,
       0, 0, 0, 0, 0)

location <-   c(rep("Location 1", 5),
              rep("Location 2", 5),
              rep("Location 3", 5),
              rep("Location 4", 5))

part <- c(rep("L", 20),
          rep("DRP", 20))


data <- data.frame(location, part, val)
data$month <- factor(c("Jan","Feb","Mar","Apr", "May"), levels = c("Jan","Feb","Mar","Apr", "May"))


ggplot(data, aes(y = val, x = month, group = part)) + 
  geom_line(aes(color = part)) + scale_x_discrete(labels = month) + facet_wrap(~location)

enter image description here