Rmarkdown docx中的R饼图

时间:2017-08-07 06:05:09

标签: r r-markdown pie-chart docx

我有一个数据,想要在Rmarkdown word_document中创建一个饼图 这是我的数据:

dt <- data.table::fread("
        TravelArea DayCounts  
            Others     98254  
             China    298705 
               USA     39048  
         SouthAsia    127046  
            Europe    114529  
        MIDAmerica      4270  
               AUS     21917 
            ENAsia    361727 
             Local   1819977 
            Africa      2473  
 AsiaPacificIsland      2943 
            ESAsia     25208  ")

Rmarkdown中的代码是:

```{r echo=FALSE, message=FALSE, warning=FALSE}
plotly::plot_ly(dt, labels = ~ TravelArea, values = ~ DayCounts, type = 'pie', 
                 textposition = 'inside', 
                 textinfo = 'label+percent', 
                 insidetextfont = list(color = '#FFFFFF'), 
                 hoverinfo = 'text', 
                 text = ~paste(TravelArea, DayCounts),
                 marker = list(colors = colors,                                                                                                                               line = list(color = '#FFFFFF', width = 1)),
                 showlegend = T) %>%
    layout(title = 'Figure C.1.1',
           xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
           yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
```

但是,这不能输出到docx。如何创建可以输出并正确显示 word_document 的饼图。

1 个答案:

答案 0 :(得分:1)

您可以尝试在此链接上给出的解决方案: 的 Plotly as png in knitr/rmarkdown

---
title: "Plot"
output: word_document
---

```{r echo=FALSE, message=FALSE}
library(plotly)

dt <- data.table::fread("
         TravelArea DayCounts  
             Others     98254  
              China    298705 
                USA     39048  
          SouthAsia    127046  
             Europe    114529  
         MIDAmerica      4270  
                AUS     21917 
             ENAsia    361727 
              Local   1819977 
             Africa      2473  
  AsiaPacificIsland      2943 
             ESAsia     25208  ")



p <- plot_ly(dt, labels = ~ TravelArea, values = ~ DayCounts, type = 'pie', 
             textposition = 'inside', 
             textinfo = 'label+percent', 
             insidetextfont = list(color = '#FFFFFF'), 
             hoverinfo = 'text', 
             text = ~paste(TravelArea, DayCounts),
             marker = list(colors = colors,                                                                
             line = list(color = '#FFFFFF', width = 1)),
             showlegend = T)  %>%
             layout(title = 'Figure C.1.1',
             xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
             yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

tmpFile <- tempfile(fileext = ".png")
export(p, file = tmpFile)

```