【问题标题】:Unable to convert ggplot2 using ggplotly无法使用 ggplotly 转换 ggplot2
【发布时间】:2021-05-16 05:53:53
【问题描述】:

我有一个ggplot2图表,代码如下

   [![enter image description here][1]][1]a <-filter(match,team==theTeam)
   # Group batsman with non strikers and compute partnerships
   df <- data.frame(summarise(group_by(a,batsman,nonStriker),sum(runs)))
   names(df) <- c("batsman","nonStriker","runs")

if(plot==TRUE){
    plot.title <- paste(theTeam,"Batting partnership in match (vs.",opposition,")")
    ggplot(data=df,aes(x=batsman,y=runs,fill=nonStriker))+
        geom_bar(data=df,stat="identity") +
        xlab("Batmen") + ylab("Runs Scored") +
        ggtitle(bquote(atop(.(plot.title),
                                atop(italic("Data source:http://cricsheet.org/"),"")))) +
        theme(axis.text.x = element_text(angle = 90, hjust = 1))

生成如下图表。

但是当我尝试用

创建一个交互式图表时
g<-ggplot(data=df,aes(x=batsman,y=runs,fill=nonStriker))+
        geom_bar(data=df,stat="identity") +
        xlab("Batmen") + ylab("Runs Scored") +
        ggtitle(bquote(atop(.(plot.title),
                                atop(italic("Data source:http://cricsheet.org/"),"")))) +
        theme(axis.text.x = element_text(angle = 90, hjust = 1))
ggplotly(g)

我收到以下错误

Error in unique.default(x) : unique() applies only to vectors
In addition: Warning message:
In if (robust_nchar(plot$labels$title) > 0) { :
the condition has length > 1 and only the first element will be used

在转换 ggplot -> ggplotly 之前有什么具体需要做的吗?

谢谢

测试数据

击球手非前锋跑 JA 莫克尔乔金德夏尔马 21 JA 莫克尔 MS Dhoni 3 JA 莫克尔 MS 戈尼 5 Joginder Sharma JA 莫克尔 16

MS Dhoni        JA Morkel       1
MS Dhoni        SK Raina        22
MS Gony JA Morkel       15
PA Patel        SP Fleming      4
S Anirudha      SP Fleming      1
S Badrinath     SK Raina        0
SK Raina        MS Dhoni        16
SK Raina        S Badrinath     9
SK Raina        SP Fleming      7
SP Fleming      S Anirudha      5
SP Fleming      SK Raina        9

【问题讨论】:

  • 添加了测试数据。
  • 这似乎有效。还需要获得副标题。 g= ggplot(data=df,aes(x=batsman,y=runs,fill=nonStriker))+ geom_bar(data=df,stat="identity") + xlab("Batmen") + ylab("Runs Scored" ) + ggtitle(plot.title) + 主题(axis.text.x = element_text(angle = 90, hjust = 1)) ggplotly(g)

标签: r ggplot2 ggplotly


【解决方案1】:

这是plotly 中的long pending open issue,其中的字幕从 ggplot -> plotly 中丢失了。现在的解决方法是在 plotly 中添加标题和副标题。

library(ggplot2)
library(plotly)

ggplot(data=df,aes(x=batsman,y=runs,fill=nonStriker))+
  geom_bar(data=df,stat="identity") +
  xlab("Batmen") + ylab("Runs Scored") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) -> g

ggplotly(g) %>%
  layout(title = list(text = paste0(plot.title, '\n<sup>Data source:http://cricsheet.org/</sup>')))

【讨论】:

猜你喜欢
  • 2019-09-10
  • 2017-08-06
  • 2019-11-23
  • 2019-01-02
  • 1970-01-01
  • 2019-06-04
  • 2020-04-02
  • 1970-01-01
相关资源
最近更新 更多