年份作为列名,熔化后成为因子,不能以正确的方式绘制

时间:2017-08-10 03:49:31

标签: r ggplot2 reshape2

我在R中使用了融合函数。在我的原始数据集中,year是列名(2000-2010)。

    try1 <- melt(<original dataset name>,id = c('Country.Name', 'Indicator.Name'))

融化后,数据集如下

    Country.Name Indicator.Name                           variable  value
    Brazil        Access to electricity (% of population) 2000      94.45697
    Brazil        Access to electricity (% of population) 2001      96.01653
    Brazil        Access to electricity (% of population) 2002      96.65300
    Brazil        Access to electricity (% of population) 2003      96.98010
    Brazil        Access to electricity (% of population) 2004      96.76511
    Brazil        Access to electricity (% of population) 2005      97.09351
    Brazil        Access to electricity (% of population) 2006      97.59431 
    Brazil        Access to electricity (% of population) 2007      98.12538
    Brazil        Access to electricity (% of population) 2008      98.52662
    Brazil        Access to electricity (% of population) 2009      98.85694
    Brazil        Access to electricity (% of population) 2010      99.16006

但是,当我检查每个变量的类时:

    str(try1)
    data.frame':    11 obs. of  4 variables:
    $ Country.Name  : chr  "Brazil" "Brazil" "Brazil" "Brazil" ...
    $ Indicator.Name: chr  "Access to electricity (% of population)" "Access 
    to electricity (% of population)" "Access to electricity (% of 
    population)" "Access to electricity (% of population)" ...
    $ variable      : Factor w/ 11 levels "2000","2001",..: 1 2 3 4 5 6 7 8 
    9 10 ...
    $ value         : num  94.5 96 96.7 97 96.8 ...

我想在每年绘制指标值的图表,如下所示;

    library(ggplot2)
    library(plotly)
    p <- ggplot(try1, aes(x = as.numeric(levels(variable))[variable], y = 
         value)) + 
         geom_point() +
         geom_line() +
         labs(title = try1$Indicator.Name[1], x = 'year', y = '%') +
         theme_economist()
   ggplotly(p)

但图中的年份值不正确,在x轴上显示为2000.0,2002.5,2005.0,2007.5,2010.0。

然而,当我检查

    as.numeric(levels(try1$variable))[try1$variable]
    [1] 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010

我也试过as.numeric(as.character(variable)),或者在melt中添加了variable.factor = FALSE,它没有帮助。

我在哪里弄错了,以及如何纠正错误?感谢

1 个答案:

答案 0 :(得分:0)

-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.2.0/modules \

希望这有帮助!