<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Arquivos Antônio Júnior - Estatidados</title>
	<atom:link href="http://estatidados.com.br/category/professores-colaboradores/antonio-junior/feed/" rel="self" type="application/rss+xml" />
	<link>http://estatidados.com.br/category/professores-colaboradores/antonio-junior/</link>
	<description>Comunidade de Estatística</description>
	<lastBuildDate>Mon, 08 Jun 2020 18:31:21 +0000</lastBuildDate>
	<language>pt-BR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Construindo um dashboard interativo com R, Shiny e Plotly</title>
		<link>http://estatidados.com.br/construindo-um-dashboard-interativo-com-r-shiny-e-plotly/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=construindo-um-dashboard-interativo-com-r-shiny-e-plotly</link>
					<comments>http://estatidados.com.br/construindo-um-dashboard-interativo-com-r-shiny-e-plotly/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 08 Jun 2020 16:36:03 +0000</pubDate>
				<category><![CDATA[Antônio Júnior]]></category>
		<category><![CDATA[Estatística]]></category>
		<category><![CDATA[Linguagens de programação]]></category>
		<category><![CDATA[Professores colaboradores]]></category>
		<guid isPermaLink="false">http://estatidados.com.br/?p=142</guid>

					<description><![CDATA[<p>Quando o objetivo é apenas usufruir de um painel interativo para acompanhamento do negócio e apoio à tomada de decisão, será que é necessário investir em uma plataforma de BI? Neste artigo vou demonstrar como construir um dashboard interativo e<a class="leiamais" href="http://estatidados.com.br/construindo-um-dashboard-interativo-com-r-shiny-e-plotly/" title="Construindo um dashboard interativo com R, Shiny e Plotly">...[Continuar lendo]</a></p>
<p>O post <a href="http://estatidados.com.br/construindo-um-dashboard-interativo-com-r-shiny-e-plotly/">Construindo um dashboard interativo com R, Shiny e Plotly</a> apareceu primeiro em <a href="http://estatidados.com.br">Estatidados</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="497" src="http://estatidados.com.br/wp-content/uploads/2020/06/shiny-1024x497.png" alt="" class="wp-image-143" srcset="http://estatidados.com.br/wp-content/uploads/2020/06/shiny-1024x497.png 1024w, http://estatidados.com.br/wp-content/uploads/2020/06/shiny-300x146.png 300w, http://estatidados.com.br/wp-content/uploads/2020/06/shiny-768x373.png 768w, http://estatidados.com.br/wp-content/uploads/2020/06/shiny-200x97.png 200w, http://estatidados.com.br/wp-content/uploads/2020/06/shiny-400x194.png 400w, http://estatidados.com.br/wp-content/uploads/2020/06/shiny-1000x486.png 1000w, http://estatidados.com.br/wp-content/uploads/2020/06/shiny-978x475.png 978w, http://estatidados.com.br/wp-content/uploads/2020/06/shiny.png 1277w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Quando o objetivo é apenas usufruir de um painel interativo para acompanhamento do negócio e apoio à tomada de decisão, será que é necessário investir em uma plataforma de BI?</p>



<p>Neste artigo vou demonstrar como construir um dashboard interativo e gratuito (desde que publicado em servidor local) com linguagem R e os pacotes Shiny e Plotly.</p>



<h3 class="wp-block-heading">Entendendo a aplicação</h3>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQExqSn2PkPOUA/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=SU5yT8x0yfg85mzYykTEPmRyCOK4KFjTZxj8_68iBzQ" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>A ideia é construir um dashboard baseado no clássico conjunto de dados&nbsp;<strong>iris</strong>, que já vem embutido na instalação do R.</p>



<p>O dashboard será composto por duas abas. A primeira,&nbsp;<strong>Histogramas</strong>, irá exibir 4 histogramas (um para cada variável quantitativa do dataset) e a segunda,&nbsp;<strong>Dispersão</strong>, exibirá 2 gráficos de dispersão para comparar comprimento de largura de sépala e pétala das espécies.</p>



<p>Se desejar, o projeto completo está no Github.&nbsp;<a href="https://github.com/juniorssz/dashboard-iris" target="_blank" rel="noreferrer noopener">Clique aqui</a>&nbsp;para acessa-lo.</p>



<h3 class="wp-block-heading">Estruturando a aplicação</h3>



<p>Antes de tudo, certifique-se que possui os pacotes&nbsp;<strong>shiny</strong>&nbsp;e&nbsp;<strong>shinydashboard</strong>&nbsp;instalados. Em seguida, no diretório escolhido, crie dois scripts:&nbsp;<strong>ui.R</strong>&nbsp;e&nbsp;<strong>server.R</strong>. A estrutura básica do Shiny é a seguinte:</p>



<pre class="wp-block-preformatted"><em># ui.R</em>

library(shinydashboard)

ui &lt;- dashboardPage(
&nbsp;&nbsp;
&nbsp; dashboardHeader(),
&nbsp;&nbsp;
&nbsp; dashboardSidebar(),
&nbsp;&nbsp;
&nbsp; dashboardBody()
)


<em># server.R</em>

library(shiny)

server &lt;- function(input, output) {

}
</pre>



<p>Para testar se tudo está funcionando corretamente, rode a aplicação. O resultado deverá ser este:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQE0PDXIz02XNg/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=nR6Yu5PWMZIIRr5po-K9hhp8YHwGl_cgBLFTaJH_U0o" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Em&nbsp;<em>dashboardHeader()</em>&nbsp;é possível incluir o nome da aplicação. Neste caso resolvi chamar de&nbsp;<strong>Dashboard Iris</strong>:</p>



<pre class="wp-block-preformatted">dashboardHeader(title = "Dashboard Iris")
</pre>



<p>Em&nbsp;<em>dashboardSidebar()</em>, inclua o menu através da função&nbsp;<em>sidebarMenu()</em>:</p>



<pre class="wp-block-preformatted">dashboardSidebar(
&nbsp; &nbsp; sidebarMenu(
&nbsp; &nbsp; &nbsp; menuItem("Histogramas", tabName = "histogramas", icon = icon("chart-bar")),
&nbsp; &nbsp; &nbsp; menuItem("Dispersão", tabName = "dispersao", icon = icon("chart-bar"))
&nbsp; &nbsp; )
&nbsp; )
</pre>



<p>E em<em>&nbsp;dashboardBody()</em>, crie as abas através da função&nbsp;<em>tabItems()</em>:</p>



<pre class="wp-block-preformatted">dashboardBody(
&nbsp; &nbsp; tabItems(
&nbsp; &nbsp; &nbsp; tabItem(tabName = "histogramas", "Testando a aba Histogramas"),
&nbsp; &nbsp; &nbsp; tabItem(tabName = "dispersao", "Testando a aba Dispersão")
&nbsp; &nbsp; )
&nbsp; )
</pre>



<p>Observe que o menu e as abas irão &#8220;conversar&#8221; através do parâmetro&nbsp;<strong>tabName</strong>.</p>



<p>Ao rodar a aplicação, a aba&nbsp;<strong>Histogramas</strong>&nbsp;será exibida assim:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQHqLQ9zJqewyw/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=lIwy_L3PCf6qerpnI2oi-YxTuVW2ddeR8naAoFLsuYM" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>E a aba&nbsp;<strong>Dispersão</strong>, assim:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQHhCGt32agKFA/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=K-GNwBCPrlBlWyA9_sqziHUNrlXAkR3227h9RVQw0tM" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Agora crie um script chamado&nbsp;<strong>data.R</strong>&nbsp;no mesmo diretório dos demais. Através dele iremos carregar o dataset. Para este exemplo, o conjunto de dados utilizado já está embutido na instalação do R, entretanto, poderíamos obter os dados através de algum banco de dados ou API, por exemplo.</p>



<pre class="wp-block-preformatted"><em># data.R</em>

df &lt;- iris
</pre>



<p>É válido mencionar que não é necessário criar um script para isso, mas acredito que desta forma o projeto fica melhor organizado.</p>



<p>Agora é necessário incluir a instruções abaixo nos scripts&nbsp;<strong>ui.R</strong>&nbsp;e&nbsp;<strong>server.</strong>R, caso contrário, o script que acabamos de criar não será enxergado pela aplicação.</p>



<pre class="wp-block-preformatted">source("data.R")
</pre>



<p>Até aqui temos construído o esqueleto da aplicação.</p>



<p>O scripts até o momento devem estar assim:</p>



<pre class="wp-block-preformatted"><em># ui.R</em>

library(shinydashboard)
source("data.R")

ui &lt;- dashboardPage(
&nbsp;&nbsp;
&nbsp; dashboardHeader(title = "Dashboard Iris"),
&nbsp;&nbsp;
&nbsp; dashboardSidebar(
&nbsp; &nbsp; sidebarMenu(
&nbsp; &nbsp; &nbsp; menuItem("Histogramas", tabName = "histogramas", icon = icon("chart-bar")),
&nbsp; &nbsp; &nbsp; menuItem("Dispersão", tabName = "dispersao", icon = icon("chart-bar"))
&nbsp; &nbsp; )
&nbsp; ),
&nbsp;&nbsp;
&nbsp; dashboardBody(
&nbsp; &nbsp; tabItems(
&nbsp; &nbsp; &nbsp; tabItem(tabName = "histogramas", "Testando a aba Histogramas"),
&nbsp; &nbsp; &nbsp; tabItem(tabName = "dispersao", "Testando a aba Dispersão")
&nbsp; &nbsp; )
&nbsp; )
)



<em># server.R</em>

library(shiny)
source("data.R")

server &lt;- function(input, output) {

}



<em># data.R</em>

df &lt;- iris
</pre>



<h3 class="wp-block-heading">Iniciando os trabalhos</h3>



<p>O layout do front-end (<strong>ui.R</strong>) pode ser orientado a linhas, a colunas ou misto. Neste exemplo vou utilizar a orientação a linhas.</p>



<p>Na aba&nbsp;<strong>histogramas</strong>, crie a primeira linha através da função&nbsp;<em>fluidRow()</em>:</p>



<pre class="wp-block-preformatted">dashboardBody(
&nbsp; &nbsp; tabItems(
&nbsp; &nbsp; &nbsp; tabItem(tabName = "histogramas",
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow()
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ),
&nbsp; &nbsp; &nbsp; tabItem(tabName = "dispersao", "Testando a aba Dispersão")
&nbsp; &nbsp; )
&nbsp; )
</pre>



<p>Agora a ideia é criar uma caixa de seleção que permita que o usuário escolha qual espécie de flor os gráficos irão exibir os dados.</p>



<p>Antes disso é necessário criar uma&nbsp;<strong>box</strong>&nbsp;para comportar a caixa de seleção:</p>



<pre class="wp-block-preformatted">dashboardBody(
&nbsp; &nbsp; tabItems(
&nbsp; &nbsp; &nbsp; tabItem(tabName = "histogramas",
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(width = 2)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; &nbsp; ),
&nbsp; &nbsp; &nbsp; tabItem(tabName = "dispersao", "Testando a aba Dispersão"
&nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; )
&nbsp; )
</pre>



<p>Observe que a largura (width) da box foi definida como 2. É importante saber que a soma das larguras de todos os componentes de uma&nbsp;<em>fluidRow()</em>&nbsp;deve resultar em 12. Ou seja, ao definirmos a box com 2 de largura, significa que o componente ocupará 1/6 da largura da linha.</p>



<p>Agora inclua dentro da box a caixa de seleção através da função&nbsp;<em>selectInput()</em>. Observe que&nbsp;<strong>select_specie</strong>&nbsp;é o identificador da caixa de seleção, ou seja, será através deste nome que ela será reconhecida pelo back-end (<strong>server.R</strong>). Outro detalhe é sobre o parâmetro&nbsp;<strong>choices</strong>, repare que as opções de escolha são as espécies de flor contidas na variável&nbsp;<strong>Species</strong>&nbsp;do dataset.</p>



<pre class="wp-block-preformatted">tabItem(tabName = "histogramas",
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(width = 2,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectInput(inputId = "select_specie", label = "Selecione a espécie",&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; choices = unique(df$Species),&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selected = 1))
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; &nbsp; )
</pre>



<p>Ao rodar a aplicação, este será o resultado:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQE63mdH-3aMRA/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=04ibwdpVfL_knI97o8V8xgLWFWrN2HFwur1JwR7nd_U" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>O primeiro histograma será criado na segunda linha do front-end e, da mesma forma que a caixa de seleção, deverá estar contido dentro de uma box.</p>



<pre class="wp-block-preformatted">tabItem(tabName = "histogramas",
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(width = 2,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectInput(inputId = "select_specie", label = "Selecione a espécie",&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; choices = unique(df$Species),&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selected = 1))
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box()
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; &nbsp; ),
</pre>



<p>Observe que desta vez não foi definida a largura da box. Isto quer dizer que a box ocupará 1/2 da largura da linha.</p>



<p>Agora, inclua dentro da box a função&nbsp;<em>plotOutput()</em>. Esta será responsável por renderizar o primeiro histograma.</p>



<pre class="wp-block-preformatted">tabItem(tabName = "histogramas",
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(width = 2,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectInput(inputId = "select_specie", label = "Selecione a espécie",&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; choices = unique(df$Species),&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selected = 1))
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; plotOutput(outputId = "hist_sepal_len"))
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; &nbsp; ),
</pre>



<p>Observe que&nbsp;<strong>hist_sepal_len</strong>&nbsp;é o identificador do histograma, que por sinal ainda não foi criado. Será através deste nome que a comunicação ira ocorrer entre front-end e back-end.</p>



<p>O próximo passo é criar o histograma no back-end.</p>



<pre class="wp-block-preformatted">server &lt;- function(input, output) {
&nbsp; output$hist_sepal_len &lt;- renderPlot({


&nbsp; })
}
</pre>



<p>Primeiro observe que o identificador do histograma criado no front-end se tornou uma variável do objeto&nbsp;<strong>output&nbsp;</strong>e que esta variável recebeu a função<em>&nbsp;renderPlot()</em>.</p>



<p>Como os dados que alimentarão o histograma serão em função da espécie selecionada pelo usuário, dentro de&nbsp;<em>renderPlot()</em>&nbsp;devemos realizar o slice, de modo que sejam selecionadas somente as observações cuja a variável&nbsp;<strong>Species</strong>&nbsp;seja igual ao valor selecionado na caixa de seleção identificada por<strong>&nbsp;select_specie</strong>.</p>



<pre class="wp-block-preformatted">server &lt;- function(input, output) {
&nbsp; output$hist_sepal_len &lt;- renderPlot({
&nbsp; &nbsp; data &lt;- df[df$Species == input$select_specie, "Sepal.Length"]

&nbsp; })
}
</pre>



<p>Por fim a função&nbsp;<em>hist()</em>&nbsp;irá plotar o histograma da variável&nbsp;<strong>Sepal.Length</strong>:</p>



<pre class="wp-block-preformatted">server &lt;- function(input, output) {
&nbsp; output$hist_sepal_len &lt;- renderPlot({
&nbsp; &nbsp; data &lt;- df[df$Species == input$select_specie, "Sepal.Length"]
&nbsp; &nbsp; hist(data)
&nbsp; })
}
</pre>



<p>E este é o resultado ao rodar a aplicação:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQGZJF65hiNtPg/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=xQYcqTzSgU0SAYwhosGYOUFJaaNjF_XGEPbnlqCL8M4" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Decepcionante, não? Mas o pacote&nbsp;<strong>ggplot2</strong>&nbsp;pode ajudar a melhorar este histograma (certifique-se que ele esteja instalado).</p>



<p>Para carregar o&nbsp;<strong>ggplot2</strong>, inclua a instrução abaixo nos scripts&nbsp;<strong>ui.R</strong>&nbsp;e&nbsp;<strong>server.R</strong>:</p>



<pre class="wp-block-preformatted">library(ggplot2)
</pre>



<p>Agora, para evitar a repetição de código, em&nbsp;<strong>data.R</strong>&nbsp;crie uma função para plotar um histograma através do&nbsp;<strong>ggplot2</strong>. No exemplo abaixo chamei a função de&nbsp;<em>plot.histogram()</em>:</p>



<pre class="wp-block-preformatted">plot.histogram &lt;- function(df, var, xlab, ylab) {
&nbsp; out &lt;- ggplot(df, aes_string(x = var)) +
&nbsp; &nbsp; geom_histogram(bins = 15, fill = "#42c2f5", color = "white", alpha = 0.7) +
&nbsp; &nbsp; labs(x = xlab, y = ylab)
&nbsp; return(out)
}
</pre>



<p>Para mais detalhes de como utilizar o ggplot2, acesse&nbsp;<a href="https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf" target="_blank" rel="noreferrer noopener">este documento</a>.</p>



<p>Agora que a função está criada, algumas alterações devem ser feitas no back-end. A primeira delas é alterar o slice para que o produto final seja um data frame e não um vetor:</p>



<pre class="wp-block-preformatted">data &lt;- df[df$Species == input$select_specie, ]
</pre>



<p>Na sequencia, substitua a função&nbsp;<em>hist()</em>&nbsp;por&nbsp;<em>plot.histogram()</em>:</p>



<pre class="wp-block-preformatted">plot &lt;- plot.histogram(data, "Sepal.Length", "Comprimento de Sépala", "Frequência")
&nbsp; &nbsp; plot
</pre>



<p>O script&nbsp;<strong>server.R</strong>&nbsp;deverá ficar assim:</p>



<pre class="wp-block-preformatted">library(shiny)
library(ggplot2)
source("data.R")


server &lt;- function(input, output) {
&nbsp; output$hist_sepal_len &lt;- renderPlot({
&nbsp; &nbsp; data &lt;- df[df$Species == input$select_specie, ]
&nbsp; &nbsp; plot &lt;- plot.histogram(data, "Sepal.Length", "Comprimento de Sépala", "Frequência")
&nbsp; &nbsp; plot
&nbsp; })
}
</pre>



<p>Ao rodar a aplicação, o resultado será este:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQGIeRkqVtvXsg/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=oUWEOQyUheosH97cEU8ORtICWo_LvbDnZdSVPQRW0Ug" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Observe que o gráfico muda quando outra espécie é selecionada através da caixa de seleção:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQHNZ9s4s-TMqA/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=Qx1NKj1koA_aghXbmyqH01IPbz9APRarmCQdkenZG2c" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Mas ainda não podemos dizer que este gráfico está interativo. Para isto vamos precisar do pacote&nbsp;<strong>plotly</strong>&nbsp;(certifique-se que ele esteja instalado).</p>



<p>Para carregar o plotly inclua a instrução abaixo no script&nbsp;<strong>ui.R</strong>:</p>



<pre class="wp-block-preformatted">library(plotly)
</pre>



<p>Ainda em&nbsp;<strong>ui.R</strong>, substitua a função&nbsp;<em>plotOutput()</em>&nbsp;por&nbsp;<em>plotlyOutput()</em>:</p>



<pre class="wp-block-preformatted">box(
&nbsp; &nbsp; plotlyOutput(outputId = "hist_sepal_len"))
</pre>



<p>O script deverá ficar assim:</p>



<pre class="wp-block-preformatted">library(shinydashboard)
library(ggplot2)
library(plotly)
source("data.R")

ui &lt;- dashboardPage(
&nbsp;&nbsp;
&nbsp; dashboardHeader(title = "Dashboard Iris"),
&nbsp;&nbsp;
&nbsp; dashboardSidebar(
&nbsp; &nbsp; sidebarMenu(
&nbsp; &nbsp; &nbsp; menuItem("Histogramas", tabName = "histogramas", icon = icon("chart-bar")),
&nbsp; &nbsp; &nbsp; menuItem("Dispersão", tabName = "dispersao", icon = icon("chart-bar"))
&nbsp; &nbsp; )
&nbsp; ),
&nbsp;&nbsp;
&nbsp; dashboardBody(
&nbsp; &nbsp; tabItems(
&nbsp; &nbsp; &nbsp; tabItem(tabName = "histogramas",
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(width = 2,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectInput(inputId = "select_specie", label = "Selecione a espécie",&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; choices = unique(df$Species),&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selected = 1))
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; plotlyOutput(outputId = "hist_sepal_len"))
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; &nbsp; ),
&nbsp; &nbsp; &nbsp; tabItem(tabName = "dispersao", "Testando a aba Dispersão"
&nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; )
&nbsp; )
)
</pre>



<p>Em seguida, em&nbsp;<strong>server.R</strong>, substitua a função&nbsp;<em>renderPlot()</em>&nbsp;por&nbsp;<em>renderPlotly()&nbsp;</em>e, ao invés de chamar o gráfico através do objeto&nbsp;<strong>plot</strong>, utilize a função&nbsp;<em>ggplotly().</em></p>



<pre class="wp-block-preformatted">server &lt;- function(input, output) {
&nbsp; output$hist_sepal_len &lt;- renderPlotly({
&nbsp; &nbsp; data &lt;- df[df$Species == input$select_specie, ]
&nbsp; &nbsp; plot &lt;- plot.histogram(data, "Sepal.Length", "Comprimento de Sépala", "Frequência")
&nbsp; &nbsp; ggplotly(plot)
&nbsp; })
}
</pre>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQH2d4Sn1uM84A/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=mS6oDpg9xTtjFJdlLIDsQ3PcL9PmWRlCCn_XvmdGkF8" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Ao rodar a aplicação, passe o mouse por cima do histograma e observe que agora ele irá possuir um menu para interação.</p>



<p>Para conhecer mais sobre a integração entre Plotly e Ggplot2, acesse&nbsp;<a href="https://plot.ly/ggplot2/" target="_blank" rel="noreferrer noopener">esta documentação</a>.</p>



<p>Para criar os outros três histogramas o processo é exatamente o mesmo. As únicas coisas que irão mudar em cada plot é o identificador de cada gráfico (outputId) e o nome da variável.</p>



<p>Após as inclusões no código, o corpo do front-end ficará assim:</p>



<pre class="wp-block-preformatted">&nbsp; dashboardBody(
&nbsp; &nbsp; tabItems(
&nbsp; &nbsp; &nbsp; tabItem(tabName = "histogramas",
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(width = 2,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectInput(inputId = "select_specie", label = "Selecione a espécie",&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; choices = unique(df$Species),&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selected = 1))
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; plotlyOutput(outputId = "hist_sepal_len")),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; plotlyOutput(outputId = "hist_sepal_wid")),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; plotlyOutput(outputId = "hist_petal_len")),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; plotlyOutput(outputId = "hist_petal_wid"))
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; &nbsp; ),
&nbsp; &nbsp; &nbsp; tabItem(tabName = "dispersao", "Testando a aba Dispersão"
&nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; )
&nbsp; )
</pre>



<p>Observe que, conforme mencionado anteriormente, quando não é especificada a largura da box, por padrão ela assume 1/2 da largura da linha. Isto quer dizer que neste caso, como são quatro boxes, ficarão duas em cada linha.</p>



<p>E o back-end ficará assim:</p>



<pre class="wp-block-preformatted">library(shiny)
library(ggplot2)
source("data.R")


server &lt;- function(input, output) {
&nbsp;&nbsp;
&nbsp; output$hist_sepal_len &lt;- renderPlotly({
&nbsp; &nbsp; data &lt;- df[df$Species == input$select_specie, ]
&nbsp; &nbsp; plot &lt;- plot.histogram(data, "Sepal.Length", "Comprimento de Sépala", "Frequência")
&nbsp; &nbsp; ggplotly(plot)
&nbsp; })
&nbsp;&nbsp;
&nbsp; output$hist_sepal_wid &lt;- renderPlotly({
&nbsp; &nbsp; data &lt;- df[df$Species == input$select_specie, ]
&nbsp; &nbsp; plot &lt;- plot.histogram(data, "Sepal.Width", "Largura de Sépala", "Frequência")
&nbsp; &nbsp; ggplotly(plot)
&nbsp; })
&nbsp;&nbsp;
&nbsp; output$hist_petal_len &lt;- renderPlotly({
&nbsp; &nbsp; data &lt;- df[df$Species == input$select_specie, ]
&nbsp; &nbsp; plot &lt;- plot.histogram(data, "Petal.Length", "Comprimento de Pétala", "Frequência")
&nbsp; &nbsp; ggplotly(plot)
&nbsp; })
&nbsp;&nbsp;
&nbsp; output$hist_petal_wid &lt;- renderPlotly({
&nbsp; &nbsp; data &lt;- df[df$Species == input$select_specie, ]
&nbsp; &nbsp; plot &lt;- plot.histogram(data, "Petal.Width", "Largura de Pétala", "Frequência")
&nbsp; &nbsp; ggplotly(plot)
&nbsp; })
}
</pre>



<p>Ao rodar a aplicação, este será o resultado:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQEHmYcgSwSUgQ/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=TAg3ci-Nyu0PxCFwi8X1DhtSaSLMLEtxMRd-3LkMZj4" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQHLgY0gNX2syg/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=Y5gfBIjn61IfOjKo_HSjtDtX1FYSHqdZUBlz-rx0sDM" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Observe que ficou um espaço em branco na primeira linha, ao lado da caixa de seleção. Podemos preencher este espaço com componentes do tipo&nbsp;<strong>value box</strong>. A largura da caixa de seleção é 2, isto quer dizer que é possível incluir mais cinco objetos com 2 de largura na mesma linha.</p>



<p>A ideia é criar cinco&nbsp;<strong>value boxes</strong>&nbsp;de modo que exibam os seguintes valores:</p>



<ol class="wp-block-list"><li>Quantidade de observações</li><li>Comprimento médio de sépala</li><li>Largura média de sépala</li><li>Comprimento médio de pétala</li><li>Largura média de pétala</li></ol>



<p>E estes valores devem ser exibidos de acordo com a espécie selecionada pelo usuário.</p>



<p>Assim sendo, na primeira linha do front-end, inclua as cinco&nbsp;<strong>value boxes</strong>&nbsp;através da função&nbsp;<em>valueBoxOutput()</em>:</p>



<pre class="wp-block-preformatted">fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(width = 2,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectInput(inputId = "select_specie", label = "Selecione a espécie",&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; choices = unique(df$Species),&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selected = 1)),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valueBoxOutput(width = 2, outputId = "value_observations"),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valueBoxOutput(width = 2, outputId = "value_sepal_len_mean"),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valueBoxOutput(width = 2, outputId = "value_sepal_wid_mean"),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valueBoxOutput(width = 2, outputId = "value_petal_len_mean"),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; valueBoxOutput(width = 2, outputId = "value_petal_wid_mean")
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ),
</pre>



<p>E no back-end, inclua as cinco outputs. Observe que desta vez, ao invés de utilizar a função&nbsp;<em>renderPlotly()</em>, a função&nbsp;<em>renderValueBox()</em>&nbsp;deve ser utilizada:</p>



<pre class="wp-block-preformatted">output$value_observations &lt;- renderValueBox({
&nbsp; &nbsp; valueBox(
&nbsp; &nbsp; &nbsp; nrow(df[df$Species == input$select_specie, ]), "Unidades Observadas", icon = icon("list"),
&nbsp; &nbsp; &nbsp; color = "blue"
&nbsp; &nbsp; )
&nbsp; })
&nbsp;&nbsp;
&nbsp; output$value_sepal_len_mean &lt;- renderValueBox({
&nbsp; &nbsp; valueBox(
&nbsp; &nbsp; &nbsp; round(mean(df[df$Species == input$select_specie, "Sepal.Length"]),1), "Compr. Médio Sépala", icon = icon("calculator"),
&nbsp; &nbsp; &nbsp; color = "teal"
&nbsp; &nbsp; )
&nbsp; })
&nbsp;&nbsp;
&nbsp; output$value_sepal_wid_mean &lt;- renderValueBox({
&nbsp; &nbsp; valueBox(
&nbsp; &nbsp; &nbsp; round(mean(df[df$Species == input$select_specie, "Sepal.Width"]),1), "Largura Média Sépala", icon = icon("calculator"),
&nbsp; &nbsp; &nbsp; color = "navy"
&nbsp; &nbsp; )
&nbsp; })
&nbsp;&nbsp;
&nbsp; output$value_petal_len_mean &lt;- renderValueBox({
&nbsp; &nbsp; valueBox(
&nbsp; &nbsp; &nbsp; round(mean(df[df$Species == input$select_specie, "Petal.Length"]),1), "Compr. Médio Pétala", icon = icon("calculator"),
&nbsp; &nbsp; &nbsp; color = "light-blue"
&nbsp; &nbsp; )
&nbsp; })
&nbsp;&nbsp;
&nbsp; output$value_petal_wid_mean &lt;- renderValueBox({
&nbsp; &nbsp; valueBox(
&nbsp; &nbsp; &nbsp; round(mean(df[df$Species == input$select_specie, "Petal.Width"]),1), "Largura Média Pétala", icon = icon("calculator"),
&nbsp; &nbsp; &nbsp; color = "purple"
&nbsp; &nbsp; )
&nbsp; })
</pre>



<p>Os ícones utilizados são provenientes&nbsp;<a href="https://fontawesome.com/icons" target="_blank" rel="noreferrer noopener">desta página</a>.</p>



<p>Ao rodar a aplicação, o resultado será este:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQE89xJeSkwHeA/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=DlPrvR_zLoLdDkfhhQHhurck81AoKl_e-bvA-QZOknQ" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Repare que os valores se alteram quando outra espécie é selecionada:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQEdkE_cKQu1iA/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=T6LivvYSyxlXW1AoISUjfr-qM6FUd_FnSEbWf3-uvXU" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Para finalizar, na aba&nbsp;<strong>Dispersão</strong>&nbsp;serão criados dois gráficos de dispersão. O processo é exatamente o mesmo utilizado com os histogramas, as únicas diferenças estão na função do&nbsp;<strong>ggplot2</strong>&nbsp;e que estes não dependerão de um objeto de entrada, como a caixa de seleção utilizada na aba&nbsp;<strong>Histogramas</strong>.</p>



<p>Para prosseguir, pelo mesmo motivo dos histogramas, crie uma função para plotar os gráficos de dispersão em&nbsp;<strong>data.R</strong>. No exemplo chamei a função de&nbsp;<em>plot.scatter()</em>:</p>



<pre class="wp-block-preformatted">plot.scatter &lt;- function(df, var.x, var.y, c.factor, xlab, ylab, lname) {
&nbsp; out &lt;- ggplot(df, aes_string(x = var.x, y = var.y, color = c.factor)) +
&nbsp; &nbsp; geom_point() +
&nbsp; &nbsp; labs(x = xlab, y = ylab) +
&nbsp; &nbsp; scale_color_discrete(name = lname)
&nbsp; return(out)
}
</pre>



<p>No front-end, a aba&nbsp;<strong>dispersão</strong>&nbsp;ficará da seguinte forma:</p>



<pre class="wp-block-preformatted">tabItem(
&nbsp; &nbsp; &nbsp; &nbsp; tabName = "dispersao",
&nbsp; &nbsp; &nbsp; &nbsp; fluidRow(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; plotlyOutput(outputId = "scatter_1")),
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; box(
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; plotlyOutput(outputId = "scatter_2"))
&nbsp; &nbsp; &nbsp; &nbsp; )
&nbsp; &nbsp; &nbsp; )
</pre>



<p>E no back-end, inclua as duas outputs:</p>



<pre class="wp-block-preformatted">output$hist_petal_len &lt;- renderPlotly({
&nbsp; &nbsp; data &lt;- df[df$Species == input$select_specie, ]
&nbsp; &nbsp; plot &lt;- plot.histogram(data, "Petal.Length", "Comprimento de Pétala", "Frequência")
&nbsp; &nbsp; ggplotly(plot)
&nbsp; })
&nbsp;&nbsp;
&nbsp; output$hist_petal_wid &lt;- renderPlotly({
&nbsp; &nbsp; data &lt;- df[df$Species == input$select_specie, ]
&nbsp; &nbsp; plot &lt;- plot.histogram(data, "Petal.Width", "Largura de Pétala", "Frequência")
&nbsp; &nbsp; ggplotly(plot)
&nbsp; })
</pre>



<p>Ao rodar a aplicação, a aba&nbsp;<strong>Dispersão</strong>&nbsp;ficará da seguinte forma:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQEWKbggvq4IbQ/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=P4kNIn43aHJe44uvLEyv4Zlo8AeZW-J8AiXSSDdJktA" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Pronto, dashboard finalizado! É claro que existem outras inúmeras opções de customização. Para saber mais detalhes, acesse a&nbsp;<a href="https://rstudio.github.io/shinydashboard/" target="_blank" rel="noreferrer noopener">documentação</a>&nbsp;do&nbsp;<strong>shinydashboard</strong>.</p>



<p>É possível publicar a aplicação em um serviço web da RStudio, o<a href="https://www.shinyapps.io/" target="_blank" rel="noreferrer noopener">shinyapps.io</a>, no entanto, o plano free possui algumas limitações. Este dashboard, inclusive, foi publicado através deste serviço e você pode acessá-lo&nbsp;<a href="https://juniorssz.shinyapps.io/dashboard-iris/" target="_blank" rel="noreferrer noopener">clicando aqui</a>&nbsp;(o primeiro acesso pode demorar um pouco para renderizar os gráficos).</p>



<p>Lembro que a publicação em servidor local pode ser realizada sem custos.</p>



<h3 class="wp-block-heading">Conclusão</h3>



<p>Se o objetivo é apenas usufruir de um painel interativo para o acompanhamento do negócio e apoio à tomada de decisão, uma solução baseada em R e Shiny pode ser suficiente, pois além de ser bastante versátil e customizável, pode ser implementada sem custos.</p>



<p>Por <em>Antonio Júnior</em><br><a rel="noreferrer noopener" href="https://www.linkedin.com/in/juniorssz/" target="_blank">https://www.linkedin.com/in/juniorssz/</a></p>



<h3 class="wp-block-heading">Referências e links úteis</h3>



<ul class="wp-block-list"><li><a href="https://shiny.rstudio.com/" target="_blank" rel="noreferrer noopener">https://shiny.rstudio.com</a></li><li><a href="https://rstudio.github.io/shinydashboard/" target="_blank" rel="noreferrer noopener">https://rstudio.github.io/shinydashboard/</a></li><li><a href="https://www.shinyapps.io/" target="_blank" rel="noreferrer noopener">https://www.shinyapps.io</a></li><li><a href="https://plot.ly/ggplot2/" target="_blank" rel="noreferrer noopener">https://plot.ly/ggplot2/</a></li><li><a href="https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf" target="_blank" rel="noreferrer noopener">https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf</a></li><li><a href="https://fontawesome.com/icons" target="_blank" rel="noreferrer noopener">https://fontawesome.com/icons</a></li><li><a href="http://leg.ufpr.br/~walmes/cursoR/data-vis/04-vis-interactive.html" target="_blank" rel="noreferrer noopener">http://leg.ufpr.br/~walmes/cursoR/data-vis/04-vis-interactive.html</a></li><li><a href="https://github.com/pet-estatistica/iguir2/tree/master/shiny" target="_blank" rel="noreferrer noopener">https://github.com/pet-estatistica/iguir2/tree/master/shiny</a></li><li><a href="https://github.com/pet-estatistica/labestData/tree/devel/inst/ShinyApps/labestDataView" target="_blank" rel="noreferrer noopener">https://github.com/pet-estatistica/labestData/tree/devel/inst/ShinyApps/labestDataView</a></li><li><a href="http://shiny.leg.ufpr.br/" target="_blank" rel="noreferrer noopener">http://shiny.leg.ufpr.br/</a></li><li><a href="https://juniorssz.shinyapps.io/dashboard-iris/" target="_blank" rel="noreferrer noopener">https://juniorssz.shinyapps.io/dashboard-iris/</a></li><li><a href="https://github.com/juniorssz/dashboard-iris" target="_blank" rel="noreferrer noopener">https://github.com/juniorssz/dashboard-iris</a></li></ul>



<p>Live Shiny -Fernando Barbalho:</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Live Fernando Barbalho - Auditor do Tesouro Nacional - Introdução e Projetos feitos em Shiny" width="500" height="281" src="https://www.youtube.com/embed/bQUWcc587UY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
<p>O post <a href="http://estatidados.com.br/construindo-um-dashboard-interativo-com-r-shiny-e-plotly/">Construindo um dashboard interativo com R, Shiny e Plotly</a> apareceu primeiro em <a href="http://estatidados.com.br">Estatidados</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://estatidados.com.br/construindo-um-dashboard-interativo-com-r-shiny-e-plotly/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Interface &#8220;drag and drop&#8221;​ para construção de gráficos no R</title>
		<link>http://estatidados.com.br/interface-drag-and-drop%e2%80%8b-para-construcao-de-graficos-no-r/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=interface-drag-and-drop%25e2%2580%258b-para-construcao-de-graficos-no-r</link>
					<comments>http://estatidados.com.br/interface-drag-and-drop%e2%80%8b-para-construcao-de-graficos-no-r/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 08 Jun 2020 16:24:20 +0000</pubDate>
				<category><![CDATA[Antônio Júnior]]></category>
		<category><![CDATA[Estatística]]></category>
		<category><![CDATA[Linguagens de programação]]></category>
		<category><![CDATA[Professores colaboradores]]></category>
		<guid isPermaLink="false">http://estatidados.com.br/?p=136</guid>

					<description><![CDATA[<p>A linguagem R possui excelentes recursos para uma boa análise descritiva, principalmente quando o assunto é visualização de dados. No entanto, a necessidade de digitar algumas linhas de código para conseguir plotar determinado gráfico pode complicar o trabalho de quem<a class="leiamais" href="http://estatidados.com.br/interface-drag-and-drop%e2%80%8b-para-construcao-de-graficos-no-r/" title="Interface &#8220;drag and drop&#8221;​ para construção de gráficos no R">...[Continuar lendo]</a></p>
<p>O post <a href="http://estatidados.com.br/interface-drag-and-drop%e2%80%8b-para-construcao-de-graficos-no-r/">Interface &#8220;drag and drop&#8221;​ para construção de gráficos no R</a> apareceu primeiro em <a href="http://estatidados.com.br">Estatidados</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img decoding="async" width="923" height="510" src="http://estatidados.com.br/wp-content/uploads/2020/06/esquisse.png" alt="" class="wp-image-137" srcset="http://estatidados.com.br/wp-content/uploads/2020/06/esquisse.png 923w, http://estatidados.com.br/wp-content/uploads/2020/06/esquisse-300x166.png 300w, http://estatidados.com.br/wp-content/uploads/2020/06/esquisse-768x424.png 768w, http://estatidados.com.br/wp-content/uploads/2020/06/esquisse-200x111.png 200w, http://estatidados.com.br/wp-content/uploads/2020/06/esquisse-400x221.png 400w, http://estatidados.com.br/wp-content/uploads/2020/06/esquisse-860x475.png 860w" sizes="(max-width: 923px) 100vw, 923px" /></figure>



<p>A linguagem R possui excelentes recursos para uma boa análise descritiva, principalmente quando o assunto é visualização de dados. No entanto, a necessidade de digitar algumas linhas de código para conseguir plotar determinado gráfico pode complicar o trabalho de quem ainda não tem tanta fluência com a linguagem, pois convenhamos que interromper toda hora a nossa linha de raciocínio para pesquisar “como fazer” atrapalha um pouco.</p>



<p>O&nbsp;<em>ggplot2</em>&nbsp;é um excelente pacote para visualização de dados, inclusive publiquei&nbsp;<a href="https://www.linkedin.com/pulse/visualizando-dados-em-r-com-ggplot2-antonio-c-da-silva-j%C3%BAnior/" target="_blank" rel="noreferrer noopener">este post</a>&nbsp;sobre ele, porém é necessário um pouco de prática até adquirir fluência para redigir suas linhas de código e, consequentemente, plotar os visuais desejados, entretanto, o pacote&nbsp;<strong>esquisse</strong>&nbsp;pode tornar a nossa vida um pouco mais fácil.</p>



<p>De acordo com a documentação do pacote, o&nbsp;<em>esquisse</em>&nbsp;é um&nbsp;<em>add-in</em>&nbsp;que nos permite explorar interativamente os dados, visualizando-os com o pacote&nbsp;<em>ggplot2</em>. Em outras palavras, ao invés de digitar linhas de código, basicamente o que precisamos é arrastar a soltar as variavés e pronto, o gráfico está construído!</p>



<p>Vamos ver como esta mágica funciona.</p>



<h2 class="wp-block-heading">Passo a passo</h2>



<p>Para este exemplo de uso vamos precisar somente dos pacotes&nbsp;<em>esquisse</em>&nbsp;e&nbsp;<em>ggplot2</em>:</p>



<pre class="wp-block-preformatted">install.packages("esquisse")
install.packages("ggplot2")
</pre>



<p>Em seguida carregamos os pacotes:</p>



<pre class="wp-block-preformatted">library(esquisse)
library(ggplot2)
</pre>



<p>A idéia aqui é utilizar o famoso conjunto de dados&nbsp;<em>iris</em>.</p>



<pre class="wp-block-preformatted">data(iris)
</pre>



<p>Aqui as primeiras linhas do dataset:</p>



<pre class="wp-block-preformatted">head(iris)
</pre>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQHtSdx7TGFrkA/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=iszM6eG1vzH7zRj7sbCPjGZx7OmwIlCEGDdfj4pwPWI" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Uma vez que os pacotes e o dataset estão carregados, basta chamar a função&nbsp;<em>esquisser()&nbsp;</em>passando o dataset como argumento:</p>



<pre class="wp-block-preformatted">esquisser(iris)
</pre>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQEh0bgWUQG86w/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=ZGlYUiQZjLT2WegIOIFIUoNNeAWgEA1Hfld-XmwdUJg" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>E agora começa a brincadeira. Escolhi aleatoriamente a variável&nbsp;<em>Sepal.Length</em>&nbsp;e arrastei para o eixo&nbsp;<em>x</em>. Um histograma foi gerado automaticamente:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQHwCkAJBFOpGw/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=YvoAkWxPl8B7t0wihngErY0xNvvByBhvheSRtvQ8-fQ" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Dependendo das variáveis em questão, é possível alterar o tipo do gráfico:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQFTJ-E2ajx4yw/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=rAmRqO92Ptkpq-mefo2ArEbHIklxvID4YWEZi6U0gwk" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Mas vamos continuar com o histograma. No menu&nbsp;<strong>Plot options</strong>&nbsp;encontramos configurações específicas do tipo de gráfico. Neste caso, podemos alterar, por exemplo, o número de bins:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQEEnt5Syu27Sw/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=RY4seWtn5WQvdxts9jFSMiR0ZQDdCxNd-j1YxXa75co" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>No menu&nbsp;<strong>Data</strong>&nbsp;é possível aplicar filtros no dataset:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQERLtAJLkedoA/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=ZlynE8zP0GSnDvNV1VWbJn6_4pS3mnLG2GXOCO5q9PY" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Arrastanto, por exemplo, a variável&nbsp;<em>Petal.Length</em>&nbsp;para o eixo&nbsp;<em>y</em>, temos um gráfico de dispersão:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQEx1dmj09cG5Q/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=29-2VGeP8UE_mVJNKQ6XHjxY2iyo4vNg2WCfSsNpDjY" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Podemos aumentar o tamanho dos pontos e alterar a cor, por exemplo:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQGH1F0KqESxig/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=rP01ey4HG5oN_SgugAKT6i-e7wF3knLBnbWOrsLwgdk" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Ainda no menu&nbsp;<strong>Plot options</strong>&nbsp;é possível incluir uma curva de regressão não paramétrica, ativando&nbsp;<em>Smooth line</em>:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQG06o44z7Kdlg/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=iHrifq6sSUpCwavPgk4fo5RvDyr6na8ElC6MQXxtN5k" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQEsMnMf4MSBqg/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=-8b9jbe9wu8pgcXveYylEE5RPbq6tfOWyIs4CH_yHik" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Arrastando uma variável categórica para&nbsp;<em>group</em>, agrupamos por categoria:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQE969k88GZx3g/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=gX6SEb3n1ZX9v6MZLlGR51GKugnBe3bAsY2PDCMmFjk" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Podemos criar facetas apenas arrastando uma variável categórica para&nbsp;<em>facet</em>:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQH-QPmx_tpqRw/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=b-pT8gi0elR_PLUNALAingpnKyt4hA4so0tAS5xJg9A" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Para melhorar a visualização, podemos alterar o tema em&nbsp;<strong>Plot options</strong>:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQFt8eK7JbJLCQ/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=eZ2paJpEV-5CnPYypaSHM36-GI9u7UbdgtykROUt6kU" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQEbxCYU0UYeRg/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=ScegtVu8vRv31M7ytVgahuZ5KMTJTwpzl9b-loc_Cbc" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Arrastando uma variável numérica para&nbsp;<em>size</em>, os tamanhos dos pontos são ajustados proporcionalmente:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C5612AQF8nSw22MDl9w/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=MfSO9ikLSVBB9dd3qeOAB6cO4P0eq2wdz-3jzf9wzHk" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Podemos também criar um gráfico de barras. Para isto, basta arrastar uma variável categórica para o eixo&nbsp;<em>x</em>:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQGpQaO9Grs25g/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=HYD1rPS27wghf256Hibi_wIE03qIJfbk5_PxDlwP0ek" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Arrastando, por exemplo, a variável&nbsp;<em>Sepal.Width</em>&nbsp;para o eixo&nbsp;<em>y</em>, temos boxplots:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQHdonY-fg6XyQ/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=HzLQpuOFc1tdum_1i8kg72fNafcWqiovssP0tnYF6hk" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>E para colorir os gráficos em função de uma variável, basta arrastar a respectiva variável para&nbsp;<em>fill</em>:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQG1OfLeEVwL7w/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=3MlGv_UDS7I_vd7IOLB8N6KMN8qYBL9ly_itdmmWJ9I" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Podemos customizar título, subtítulo, legenda e etc…</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQFFOO5WTM9ieQ/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=32sHuStCQ8z2iI-g1ma0Yg1u2J437qLGgtYVq7SnwDM" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQFfMiUjfwKbBQ/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=0qb4iUJ6PtZuLbPDkpUsm3ok3MEWY7NDvXx426-ECW4" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>E a ótima notícia para quem não domina o ggplot2: em&nbsp;<strong>Export &amp; code</strong>&nbsp;é possível copiar o código gerado:</p>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQEQZOMLKh-gcA/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=Mjjp2VCSLBD4viOItkvL7RTs1Dp6t0uWgiJQ__MQLNc" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<p>Perceba que o gráfico gerado através do código exportado é exatamente o mesmo:</p>



<pre class="wp-block-preformatted">ggplot(iris) +
 aes(x = Species, y = Sepal.Width, fill = Species) +
 geom_boxplot() +
 scale_fill_hue() +
 labs(x = "Nome da Espécie", y = "Largura da Sépala", title = "Espécies de Iris", subtitle = "Exemplo utilizando Esquisse", caption = "Gráfico 1", fill = "Espécie") +
 theme_minimal()
</pre>



<figure class="wp-block-image"><img decoding="async" src="https://media-exp1.licdn.com/dms/image/C4E12AQFxZ6s8r8DP_g/article-inline_image-shrink_1000_1488/0?e=1597276800&amp;v=beta&amp;t=YH_fF3CIQaVuMTYFrb-MKOoZL9eK_Phk_57KprVJyVQ" alt="Não foi fornecido texto alternativo para esta imagem"/></figure>



<h2 class="wp-block-heading">Considerações finais</h2>



<p>A página do&nbsp;esquisse&nbsp;diz que o objetivo deste pacote é permitir a exploração rápida dos dados para extrair informações, mas alerta que não é possível ainda utilizar todo o poder do&nbsp;<em>ggplot2</em>. Ou seja, o&nbsp;<em>esquisse</em>&nbsp;esta aí para agilizar a nossa análise, mas diante da necessidade de gráficos com detalhes mais complexos, talvez não seja possível através dessa interface. Portanto faça bom uso do&nbsp;<em>esquisse</em>&nbsp;nas suas análises mas não deixe de praticar o&nbsp;<em>ggplot2</em>&nbsp;raíz (por linhas de código).</p>



<p>Por <em>Antonio Júnior</em><br><a rel="noreferrer noopener" href="https://www.linkedin.com/in/juniorssz/" target="_blank">https://www.linkedin.com/in/juniorssz/</a></p>



<h2 class="wp-block-heading">Referências e materiais úteis</h2>



<ul class="wp-block-list"><li><a href="https://dreamrs.github.io/esquisse/" target="_blank" rel="noreferrer noopener">https://dreamrs.github.io/esquisse/</a></li><li><a href="https://github.com/rstudio/cheatsheets/blob/master/data-visualization-2.1.pdf" target="_blank" rel="noreferrer noopener">https://github.com/rstudio/cheatsheets/blob/master/data-visualization-2.1.pdf</a></li><li><a href="https://rstudio.com/wp-content/uploads/2016/03/ggplot2-cheatsheet-portuguese.pdf" target="_blank" rel="noreferrer noopener">https://rstudio.com/wp-content/uploads/2016/03/ggplot2-cheatsheet-portuguese.pdf</a></li><li><a href="https://www.datanovia.com/en/lessons/introduction-to-ggplot2/" target="_blank" rel="noreferrer noopener">https://www.datanovia.com/en/lessons/introduction-to-ggplot2/</a></li><li><a href="http://leg.ufpr.br/~walmes/cursoR/data-vis/03-vis-ggplot2.html" target="_blank" rel="noreferrer noopener">http://leg.ufpr.br/~walmes/cursoR/data-vis/03-vis-ggplot2.html</a></li></ul>



<p>Vídeo Esquisse e live:</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Gráficos point and click (Drag and drop) - esquisse R - Prof.  Antônio C.  da Silva" width="500" height="281" src="https://www.youtube.com/embed/KXoy005kYls?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Live Antônio Júnior - MBA em DS e Big Data pela UFPR - Análises gráficas point and click no R" width="500" height="281" src="https://www.youtube.com/embed/j3WPbtZJMeA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
<p>O post <a href="http://estatidados.com.br/interface-drag-and-drop%e2%80%8b-para-construcao-de-graficos-no-r/">Interface &#8220;drag and drop&#8221;​ para construção de gráficos no R</a> apareceu primeiro em <a href="http://estatidados.com.br">Estatidados</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://estatidados.com.br/interface-drag-and-drop%e2%80%8b-para-construcao-de-graficos-no-r/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
	</channel>
</rss>
