1

我正在尝试使用 gtrendsR 包进行绘图。每当我尝试使用该plot()函数时,R 返回的图似乎忽略了我放入其中的任何文本参数main=" ", xlab=" " or ylab=" ",这就是我的麻烦。

我也尝试过使用ggplot()

这是代码:

library(gtrendsR)
library(ggplot2)


fruits<- gtrends(c("Banana", "Apple", "Orange"), geo = c("US"), time = "2019-03-13 2019-03-27")

plot(fruits, main="I tried so hard", xlab="and got so far", ylab="but in the end")

ggplot(fruits)

ggplot(fruits$interest_over_time)

但结果更糟,因为plot()仍然给我一个图表,而ggplot()没有返回任何东西。

4

2 回答 2

2

我刚刚发现本教程Analyzing Google Trends with R: Retrieve and plot with gtrendsR与我在此处所做的描述相同,但更深入,这对您来说可能是一个很好的开始!


Fruits 不是数据框
当您调用class(fruits)if will give"gtrends" "list"能够绘制它时,您必须以数据框格式从该对象中提取您想要的信息。View(fruits)例如,如果您在 Rstudio 中工作,或者只需键入fruits$并点击选项卡, 请查看对象中的数据框。

在此处输入图像描述

我不知道你想要什么信息?但是假设您要绘制interest_by_region,那么我们通过fruit.df <- fruits$interest_by_region

再次绘制它
从你的问题中不清楚你想要绘制什么,但现在你有一个数据框(fruit.df)你可以绘制任何你想要使用ggplot2的东西,例如:

fruit.df <- fruits$interest_by_region
ggplot(fruit.df, aes(x=location, y=hits, fill = keyword)) +
  geom_bar(stat='identity') +
  coord_flip() +
  ggtitle("I tried so hard") +
  xlab("and got so far") +
  ylab("but in the end")

这会给你这个情节:

在此处输入图像描述 Ps credtis to "Linkin Park-in the end" for main,xlab and ylab haha​​h

总结
所以你要做的是:

  • 从 gtrends 对象获取数据帧,可以是interest_over_timeinterest_by_region、或. 按照我的描述执行此操作interest_by_dmainterest_by_cityrelated_queriesinterest_by_region
  • 使用 ggplot2 从这个数据框中绘制任何你想要的东西(如果你不确定如何做,请参阅ggplot2 教程)
于 2019-04-13T13:20:00.943 回答
1

您应该使用labs包的功能,ggplot2 如下所示:

plot(fruits) + labs(title = "I tried so hard", x = "and got so far", y = "but in the end")

输出:

在此处输入图像描述

说明:函数 图用于gtrendsR对象,因此使用的绘图方法gtrendsR::plot.gtrends具有以下定义:

function (x, ...) 
{
    df <- x$interest_over_time
    df$hits <- if (typeof(df$hits) == "character") {
        as.numeric(gsub("<", "", df$hits))
    }
    else {
        df$hits
    }
    df$legend <- paste(df$keyword, " (", df$geo, ")", sep = "")
    p <- ggplot(df, aes_string(x = "date", y = "hits", color = "legend")) + 
        geom_line() + xlab("Date") + ylab("Search hits") + ggtitle("Interest over time") + 
        theme_bw() + theme(legend.title = element_blank())
    print(p)
    invisible(p)
}

如您所见,该方法使用ggplot2包进行绘图(而不是 R 基础绘图)并且已经在以下位置指定了实验室:

xlab("Date") + ylab("Search hits") + ggtitle("Interest over time")

在您的情况下需要覆盖。供您参考,我们使用函数而labs不是ggtitle,因为它是新的做事方式(参见https://ggplot2.tidyverse.org/reference/labs.html),但我们可以写:xlabylab

plot(fruits) + ggtitle("I tried so hard") + xlab("and got so far") + ylab("but in the end")
于 2019-04-13T13:29:41.227 回答