如何在gtrendsR图中添加文本?

时间:2019-04-13 12:46:59

标签: r plot gtrendsr

我正在尝试使用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()却什么也没返回。

2 个答案:

答案 0 :(得分:1)

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


水果没有数据框
调用class(fruits)时,如果可以给"gtrends" "list"进行绘制,则必须以 dataframe 格式从该对象中提取所需的信息。要查看对象中的数据帧,例如,如果您在Rstudio中工作,请执行View(fruits)或直接键入fruits$并单击Tab。

enter image description here

我不知道你想要什么信息?但是,假设您要绘制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")

哪个会给你这个情节:

enter image description here P.s。 credtis的主要名称为“ Linkin Park-最后”,xlab和ylab哈哈

摘要
因此,您需要做的是:

  • 从gtrends对象获取一个数据框,该对象可以是interest_over_timeinterest_by_regioninterest_by_dmainterest_by_cityrelated_queries。按照我对interest_by_region
  • 的描述进行操作
  • 使用ggplot2从此数据框中绘制所需内容(如果不确定如何操作,请参见ggplot2 tutorial

答案 1 :(得分:1)

您应使用labs软件包的ggplot2函数,如:

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

输出:

enter image description here

说明: 功能图用于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代替ggtitlexlabylab,因为这是新的操作方式(请参见https://ggplot2.tidyverse.org/reference/labs.html),但是我们可以写:

plot(fruits) + ggtitle("I tried so hard") + xlab("and got so far") + ylab("but in the end")