Search code examples
rplotlyflexdashboardr-plotly

How to create a pie chart with Rstudio flexdashboard?


I am new to Rstudio and I am tring to figure out how to create a dashboard with "flexdashboard"

Here is my dataset

```    Country       Refugees   
    1 Belgium         508645
    2 France         2874490
    3 Germany       10893516
    4 Ireland         142555
    5 Italy           538407
    6 Netherlands    1900518
    7 Portugal          7918
    8 Spain            89946
    9 United Kingdom 3766855

enter image description here

I am trying to create a pie chart, and here is what I enter but it does not work. After trying many variations, I never figured out how to make it work.

```{r message=FALSE, warning=FALSE, include=FALSE}

library(flexdashboard)
library(plotly)

totalref <- read.csv("F:/HU/ANLY 512/Dashboarding Lab/total.xls", header = TRUE)

plot_ly(totalref, labels= ~totalref$Country, values= ~totalref$Total, type= 'pie')
 layout (title='Persons of Concern in 9 European Countries',
    xaxis = list(showgrid=FALSE, zeroline=FALSE, showticklabels=FALSE),
    yaxis = list(showgrid=FALSE, zeroline=FALSE, showticklabels=FALSE))

```

I think I am probably on the wrong track so any advise would be appreciated.


Solution

  • Here are my remarks:

    • drop the totalref$ in the plot_ly() calls and use column names directly.
    • there is no Total column in your sample data, maybe what you wanted to use is Refugees?
    • if you use include=FALSE, the code chunck will be evaluated, but neither the code nor its output will be displayed. So remove this and replace it by echo=FALSE if you want the code not to be displayed, but the plot to appear.
    • The first argument of the layout() function is the plot itself, so it seems a pipe operator %>% is missing in your code.

    Using the sample data you provided, this line:

    totalref <- read.table(header = T, text = 
    "Country        Refugees   
    'Belgium'         508645
    'France'         2874490
    'Germany'       10893516
    'Ireland'         142555
    'Italy'           538407
    'Netherlands'    1900518
    'Portugal'          7918
    'Spain'            89946
    'United Kingdom' 3766855")
    
    plot_ly(totalref, labels = ~ Country, values = ~ Refugees, type = 'pie',
            textposition = 'inside', textinfo = 'label+percent') %>%
        layout (title='Persons of Concern in 9 European Countries',
                showlegend = TRUE)
    

    works fine for me. It gives the following result:

    • textposition = 'inside', textinfo = 'label+percent': displays the label and percent inside the graph;
    • showlegend = TRUE displays the legend.

    enter image description here