【问题标题】:Simple plotting function in RR中的简单绘图功能
【发布时间】:2012-11-03 14:14:49
【问题描述】:

我在使用 R 中的绘图函数时遇到问题。这是我目前得到的结果。

countries <- c("CHINA ", "UNITED STATES", "UNITED KINGDOM", "GERMANY")
KeyItems <- c("Pretax Income", "Total Liabilities", "Total Assets")
datA <- mean_values[mean_values$Country %in% countries & mean_values$KeyItem %in% KeyItems, ]
datA$KeyItem <- factor(datA$KeyItem, levels = KeyItems, order = TRUE)
p <- xyplot(mn_value ~ Year | KeyItem, datA, groups = datA$Country[, drop = TRUE],
            auto.key = list(space = "right"), par.settings = simpleTheme(pch = 1:5),
            type = c("p", "l"), as.table = TRUE)
print(p)

我的数据框如下所示:

    KeyItem         Year     Country                                      mn_value
172 Pretax Income   1980    SWITZERLAND                                 2.091623e+08
173 Pretax Income   1980    IRELAND                                     3.597619e+07
174 Pretax Income   1980    GERMANY                                     2.301015e+07
175 Pretax Income   1980    SWEDEN                                      4.980680e+07

它返回此错误:

Error in dat$Year == Year : 'Year' is missing

我几乎没有任何 R 经验。我只是找不到解决问题的方法。提前谢谢你。

【问题讨论】:

  • 我认为您需要花费更多时间来创建示例,因为您的示例代码根本无法运行(在您使用绘图命令之前)。我会特别注意 datA 到底是什么。
  • 请提供可重现的示例!当我尝试您的代码时,我得到 no error - 也许您在代码中省略了一行(除了在您的 xyplot 调用中没有提到 Year,并且错误消息没有t 真的与您的代码匹配)。你能找出是哪一行代码产生了错误吗?

标签: r plot lattice


【解决方案1】:

正如其他人所提到的,您的代码显然不完整,并且您似乎试图以不正确的方式在类别中构造 mean 值。因此,这是一个导致 xyplot 的工作示例,它在某些(但不是全部)方面类似于您的问题:

Values <- rpois(100*4*3, 200)
datA=data.frame(Values=Values, countries=countries, KeyItems=KeyItems)
datAaggr <- with( datA, aggregate(Values , list(KeyItems, countries) , FUN=mean)) 
# At this point you could rename the Group variables,
#    or you could have done that in the aggregate call with:
datAaggr <- with( datA, aggregate(Values , list(KeyItems=KeyItems, countries=countries) , FUN=mean)) 
# This then succeeds using the aggregated dataframe with the re-named mean values as input:

p <- xyplot(x ~ countries | KeyItems, data=datAaggr, 
             auto.key = list(space = "right"), par.settings = simpleTheme(pch = 1:5),
             type = c("p", "l"), as.table = TRUE)
print(p)

这将需要对标签进行一些进一步的工作,但这可能会被推迟,直到您学会了如何使用 data.frames 进行数据转换,这是一个在绘图任务之前的学习任务。 Lattice 绘图系统严重依赖于正确的 data.frame 输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2021-12-07
    相关资源
    最近更新 更多