facet_wrap输出不正确

时间:2018-01-26 07:06:44

标签: r ggplot2 facet-wrap

以下是我的样本数据

Sample Data

虽然所有4个日期都有移动设备和平板电脑的值,但当我尝试跨设备类别进行facet_wrap时,我的结果并非预期。与每个日期对应的所有值仅添加到桌面,而不是分布在3个类别中。

我使用的代码是

qplot(data=gaData, x=gaData$Date, y=gaData$Users, xlim = c(20170101,20170101))+
  facet_wrap(~gaData$Device.Category, ncol = 1)

我在图中看到的输出是

Sample Output

我是整个数据可视化领域的新手。我无法确定代码有什么问题。

P.S。我能够成功地将移动设备和平板电脑绘制成与单个地块相同的日期。

3 个答案:

答案 0 :(得分:0)

path.fill(with: CGBlendMode.clear, alpha: 1.0)

enter image description here

这是你想要的吗?

答案 1 :(得分:0)

希望这有帮助。

# Simulate some dummy data
dat <- data.frame(
    Date = rep(20170101:20170104, each = 3),
    Device = rep(c('D', 'M', 'T'), 4),
    Users = runif(n = 12, max = 1000, min = 10) %>% round()
)

# This is the 'base map', map variables onto aesthetics
ggplot(aes(x = Date, y = Users, col = Device), data = dat) + 
    # What kind of geometry?
    geom_line() +
    geom_point() +
    # From 1d panel to 2d
    facet_wrap(~Device, ncol = 1)

Plot Result

您也可以考虑将Date变量转换为类date

以下参考资料希望能帮助您了解ggplot2。

  1. http://tutorials.iq.harvard.edu/R/Rgraphics/Rgraphics.html
  2. http://r-statistics.co/Complete-Ggplot2-Tutorial-Part1-With-R-Code.html
  3. http://ggplot2.tidyverse.org/reference/
  4. 此外,DataCamp提供精彩的在线教程。

    欢迎来到R.干杯的惊人世界。

答案 2 :(得分:0)

首先我建议您将'Date'转换为POSIXct。我用的是lubridate包:

library(lubridate)
Date=ymd(c(rep("2017-01-01",3),rep("2017-01-02",3),rep("2017-01-03",3),rep("2017-01-04",3)))

然后我们可以构建数据帧的其余部分

Country=rep("United States",12)
Device.Category=rep(c("Desktop","Mobile","Tablet"),4)
Users=c(404,223,39,529,211,43,1195,285,29,1019,275,35)
df=data.frame(Date,Country,Device.Category,Users)

如果您只想为“2017-01-01”绘图,请使用此

ggplot(df,aes(x=Date,y=Users))+geom_point()+facet_grid(Device.Category~.)+xlim(ymd("2017-01-01"),ymd("2017-01-01"))

enter image description here

或者,如果您希望所有日期都删除xlim函数

ggplot(df,aes(x=Date,y=Users))+geom_point()+facet_grid(Device.Category~.)+xlim(ymd("2017-01-01"),ymd("2017-01-01"))

enter image description here

相关问题