2016-11-02 45 views
0

我想显示多条曲线显示多条曲线与在使用一次在GGPLOT2使用R. GGPLOT2 R中

有数据的200多个城市,但我只创建一个随机抽样数据为环如下:

#sample data 

df <- data.frame(
    city = c('paris', 'tokyo', 'seoul', 'shanghai', 'berlin', 'rome') 
    , week = c(41,42) 
    , type = c('A','B','C') 
    , count = sample(1:100, 24, replace = F) 
    ) 

df <- data.table(df) 
df[, .(count=sum(count)), by =.(city,type, week)] 

在原始数据中,有200多个城市,但我只是为此创建了随机数据。

我想根据计数数量提取排名前10位的城市, 将排名前10位的城市放入列表中, 并循环以自动绘制在查看器上。

我可以使用facet_grid选项,但为此目的,我需要以这种方式。

This article帮助我塑造到目前为止,但它不工作,因为我不是数数值,而是循环图表的因素。

# function 
plotCities <- function(cityName){ 
      df <- df[city == cityName,] 
        ggplot(df, 
          aes(x = as.factor(week), y = count, 
           color = as.factor(week), group = as.factor(week))) + 
          scale_y_continuous(labels = comma) + 
          geom_point() + 
          geom_line() + 
          labs(title = "cities monthly counts", 
           x = "month", 
           y = "counts")+ 
          theme(axis.text.x=element_text(angle=90,hjust=1,vjust=1)) 
    } 

plotCities("paris") 

这不会带来很好的图形,但并不在这一点上无论是这里的目标是绘制多个在显示。

for(cityName in df$city) { 
     plotCities(cityName) 
} 

认为这会工作,但没有创建我想要的列表...所以失败。

我的下一个尝试是:

p <- list() 
    for(i in 1:length(df$city)){ 
      cityName = df2[i, 1] 
      p[[i]] = plotCities(cityName) 

    } 

因为城市价值因素不大概工作?

请分享我一些提示!

+0

'为(的cityName在DF $市) {plottery(cityName)) }将输出图表。但是,有很多重复。所以也许增加'唯一(df $城市)' – Haboryme

+0

这个问题:http://stackoverflow.com/q/40366468/4477364有可能帮助的信息。 – Joe

回答

0

我会使用gridExtra包中的grid.arrange。这可以将多个网格图放置在一个整体图中(适用于lattice和ggplot2)。

在下面的例子中,我使用lapply(而不是for循环)来创建地块的名单,并do.call与情节名单运行grid.arrange

library(gridExtra) 
plot_list = lapply(unique(df$city), plotCities) 
do.call('grid.arrange', plot_list) 
+0

感谢您的建议!我已经尝试了这一点,并不断得到以下错误:$ _ - 。data.frame(x,name,value)中的错误: 替换有17行,数据有226 – tmhs

+0

您需要创建一个可重现的示例代码和数据,我可以复制粘贴到R并重现你的问题),因为你得到的错误可能是由许多事情造成的。没有这些信息,我无法帮助你。 –