2016-12-04 315 views
0

我正在尝试使用多个字段创建与ggplot的散点图。我已阅读了关于这些散点图和字段的着色,但想知道如何为ggplot2movies数据集执行此操作?我想颜色基础上,流派,但这些流派都分手了:R ggplot散点图颜色多列

> movies <- ggplot2movies::movies 
> head(movies) 
      title year length budget rating votes r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 mpaa Action Animation Comedy Drama Documentary Romance Short 
        <chr> <int> <dbl> <int> <dbl> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <int>  <int> <int> <int>  <int> <int> <int> 
1      $ 1971 121  NA 6.4 348 4.5 4.5 4.5 4.5 14.5 24.5 24.5 14.5 4.5 4.5   0   0  1  1   0  0  0 
2  $1000 a Touchdown 1939  71  NA 6.0 20 0.0 14.5 4.5 24.5 14.5 14.5 14.5 4.5 4.5 14.5   0   0  1  0   0  0  0 
3 $21 a Day Once a Month 1941  7  NA 8.2  5 0.0 0.0 0.0 0.0 0.0 24.5 0.0 44.5 24.5 24.5   0   1  0  0   0  0  1 
4     $40,000 1996  70  NA 8.2  6 14.5 0.0 0.0 0.0 0.0 0.0 0.0 0.0 34.5 45.5   0   0  1  0   0  0  0 
5 $50,000 Climax Show, The 1975  71  NA 3.4 17 24.5 4.5 0.0 14.5 14.5 4.5 0.0 0.0 0.0 24.5   0   0  0  0   0  0  0 
6     $pent 2000  91  NA 4.3 45 4.5 4.5 4.5 14.5 14.5 14.5 4.5 4.5 14.5 14.5   0   0  0  1   0  0  0 

什么是解决这个(基于流派的颜色)的最好方法?所有的帮助真的很感谢!

+2

我猜你将不得不收拾数据(宽长格式)。也许用'tidyr :: gather()'。 – hrbrmstr

回答

2

正如@ hrbrmstr所述,您需要将数据从宽转换为长。您可以使用tidyr::gather()dplyr::filter()一起来实现此目的。这条产业链:

  1. 汇集了来自行动短的名称和值入列genreflag。这将多列(宽)移动到键值对(长)。
  2. 使用过滤器删除genre(那些标志== 0)的多余值。
  3. 商店在plot_data

其余代码所产生的数据帧是length VS rating简单ggplot2散点图。

library(dplyr) 
library(tidyr) 
library(ggplot2) 
library(ggplot2movies) 

plot_data <- movies %>% 
    gather(genre, flag, Action:Short) %>% 
    filter(flag != 0) 

ggplot(plot_data, aes(x = rating, y = length)) + 
    geom_point(aes(color = genre), alpha = 0.4) 

enter image description here

+0

非常有帮助,而我正在寻找!谢谢 – dnsko