首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将文本添加到gtrendsR绘图?

如何将文本添加到gtrendsR绘图?
EN

Stack Overflow用户
提问于 2019-04-13 20:46:59
回答 2查看 75关注 0票数 1

我正在尝试使用gtrendsR包进行绘图。每当我尝试使用plot()函数时,R返回的图似乎忽略了我放在里面的任何文本参数,比如main=" ", xlab=" " or ylab=" ",这就是我的问题所在。

我也尝试过使用ggplot()

代码如下:

代码语言:javascript
复制
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()什么也不返回。

EN

回答 2

Stack Overflow用户

发布于 2019-04-13 21:20:01

我刚刚找到了这个教程,它描述了与我在这里相同的内容,但更深入地说,这可能是一个很好的开始!

fruits不是数据帧

当您调用class(fruits)时,如果要使"gtrends" "list"能够绘制它,您必须以数据帧格式从这个对象中提取所需的信息。要查看对象中有哪些数据帧,例如,如果您在Rstudio中工作,则执行View(fruits),或者简单地输入fruits$并按tab键。

我不知道你想要什么信息?但是假设您想要绘制interest_by_region,然后我们通过fruit.df <- fruits$interest_by_region获得数据帧

中的绘图

同样,从您的问题中还不清楚您想要绘制什么,但是现在您有了一个数据帧(fruit.df),您可以使用ggplot2绘制您想要绘制的任何内容,例如:

代码语言:javascript
复制
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")

这将会给出这个图:

附注:为main,xlab和ylab提供"Linkin Park- in the end“的证书哈哈

摘要

所以你要做的是:

  • 从gtrends对象获取数据帧,该对象可以是interest_over_timeinterest_by_regioninterest_by_dmainterest_by_cityrelated_queries。按照我在interest_by_region
  • 中所述,使用ggplot2 (如果您不确定如何操作,请参阅ggplot2 tutorial )从该数据框中绘制
票数 2
EN

Stack Overflow用户

发布于 2019-04-13 21:29:41

您应该使用ggplot2包的labs函数,如下所示:

代码语言:javascript
复制
plot(fruits) + labs(title = "I tried so hard", x = "and got so far", y = "but in the end")

以下哪项输出:

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

代码语言:javascript
复制
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基准绘图),并且已经在以下位置指定了实验:

代码语言:javascript
复制
xlab("Date") + ylab("Search hits") + ggtitle("Interest over time")

在你的情况下需要被覆盖。作为参考,我们使用函数labs而不是ggtitlexlabylab,因为这是一种新的操作方式(请参阅https://ggplot2.tidyverse.org/reference/labs.html),但我们可以这样写:

代码语言:javascript
复制
plot(fruits) + ggtitle("I tried so hard") + xlab("and got so far") + ylab("but in the end")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55665616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档