Removing the X,Y in nearPoints() Output - r

I want to use the functionality of nearPoints() to print out summary statistics for a specific point without printing the x, y associated with that point. I have been able to use this function printing the data frame and variations of the data frame. Is there anyway to suppress those columns
to customize the output? nearPoints comes from the latest version of shiny 0.12.1 but I believe may have been introduced a little earlier.
I know the documentation says this:
Note that these functions are only appropriate if the x and y variables are present in the data frame, without any transformation. If, for example, you have a plot where a the x position is calculated from a column of data, then these functions won’t work. In such a case, it may be useful to first calculate a new column and store it in the data frame.
but wanted to know if there was any kind of work around.
Here is the app that illustrates this problem, note that I'm using all of those libraries in my bigger app:
library(shiny)
library(ggplot2)
library(Cairo)
library(plyr)
library(dplyr)
library(shinydashboard)
library(grid)
library(gridExtra) # also loads grid
library(grDevices)
library(ggmap)
library(sqldf)
cars <- mtcars
ui <- basicPage(
plotOutput("plot1", click = "plot_click"),
dataTableOutput("info")
)
server <- function(input, output) {
output$plot1 <- renderPlot({
ggplot(cars, aes(x=cyl, y=carb)) + geom_point()
})
output$info <- renderDataTable({
summary_cars <- ddply(cars, .(gear, cyl, carb),
function(dd){as.data.frame(cbind(Mean_hp = mean(dd$hp),
Mean_wt = mean(dd$wt))
)
})
#This works-------------------------------------------------------
# nearPoints(summary_cars, input$plot_click, threshold = 10,
# addDist = TRUE)
#Removing the columns does not work ---------
nearPoints(select(summary_cars,-cyl,-carb), input$plot_click, threshold = 10,
addDist = F)
})
}
shinyApp(ui, server)

Related

Beginner - I want to make ggplot on Shiny in R and I don't know where I made up mistake

I am using Shiny in R to make two different tabs.
I think one tab would be a good idea to make a summary tab and another one is for the plot.
I want to give user a selection of x, y and color section... When I finished the part of ggplot section, the plot is not shown as I expected.
Please help me out where I made up mistake and please help me to understand of it.
Thank you.
# ui.R
library(shiny)
library(ggplot2)
library(plyr)
library(dplyr)
data(mtcars)
new_mtcars <- mtcars %>%
select(wt,mpg,cyl,vs,am,gear,carb)
# Define UI for an application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("prac"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("xvalue","Please Choose X Value : ", c("wt","mpg")),
selectInput("yvalue","Please Choose Y Value : ", c("wt","mpg")),
selectInput("color","Please Choose color Value : ", choices = c("cyl","vs","am","gear","carb"))
),
mainPanel(
tabsetPanel(#tabPanel("Information",tableOutput("info")),
tabPanel("Summary",tableOutput("summary")),
tabPanel("Comparison",plotOutput("plot")))
)
)
# Show a plot of the generated distribution
))
library(shiny)
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
df_sub <- reactive({
new_mtcars[,c(input$xvalue,input$yvalue,input$color)]
})
output$plot <- renderPlot({
category <- input$color
ggplot(df_sub(), aes(input$xvalue,input$yvalue)) +
geom_point(aes_(color = as.name(category)),size = 3) +
geom_smooth(method = "lm")
})
})
The issue is that input$xvalue and input$yvalue are characters. To tell ggplot that it should look for variables with these names in your dataset
use .data[[input$xvalue]] and .data[[input$yvalue]] inside aes() or
use aes_string instead of aes().

R Shiny: "Reactive" data analysis based on user input, followed by ggplot figure output

I have a basic R code where, within the code, a user can enter a country name "Argentina". Using that value/name, the code will run an analysis for the "Argentina" subset of the pre-loaded data. Finally, the code will produce a simple ggplot showing results.
I have tried to make this code into a Shiny App, however I cannot get it to work properly. My main issue is that I cannot seem to get the data analysis in the Server section to work, which should subsequently feed into the plotting code. More importantly, I cannot seem to get the user inputted country name to feed into my data analysis.
Without going into the detail of the code, could someone kindly point me in the right direction of how one would do this in Shiny? e.g.
Field for user input;
Use that user input as an object used in the code;
subsequently run the analysis (whatever it might be); and
use the final analysis data frame in ggplot for a figure output to be displayed in the shiny app.
Please see my shiny code currently used, with reproducible data using MTcars
library(shiny)
# Some Sample data to run app using mtcars
mtcars$Primary<- rownames(mtcars)
mtcars$Area <- "Argentina"
mtcars$Y2016<- mtcars$mpg
mtcars$Element <- "Gross Production Value (constant 2004-2006 million US$)"
# Defining UI ----
ui <- pageWithSidebar(
# App title ----
headerPanel("Subsector Selection Tool"),
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Country name
textInput("country", "Please enter country name", "")#,
),
# Main panel for displaying outputs ----
mainPanel("")
)
# Define server logic to plot various variables against mpg ----
server <- function(input, output) {
#Trying to make user inputed country name into an object to be used in
"reactive" code below, which in turn is be used to make dataset for graphing
country_interest <- reactive({
paste(input$country)
})
#Here I am trying to make the data analysis code run and create desired
dataset for graphing, and subsetting for country selected by user
Value_c_e_PRIM_x <- reactive({
Value_c <- Value[which(Value$Area==country_interest),]
Value_c_e <- Value_c[which(Value_c$Element=="Gross Production Value (constant 2004-2006 million US$)"),]
Value_c_e_PRIM$Primary <- Value_c_e_PRIM[,120]
Value_c_e_PRIM[,120] <- NULL
Value_c_e_PRIM <- Value_c_e_PRIM %>% group_by(Primary,Element) %>% summarise_at(vars(Y2016), sum)
Value_c_e_PRIM$Category <- "Value of Production"
Value_c_e_PRIM$Value <- Value_c_e_PRIM$Y2016
Value_c_e_PRIM <- Value_c_e_PRIM %>% group_by(Category,Primary) %>% summarise_at(vars(Value), mean)
})
#Graphing section, if Ihave the dataset "Value_c_e_PRIM_x" pre-loaded (e.g. not derived in code above), the figure is successfully shown in the output.
output$plot <- renderPlot({
Graph_data <- Value_c_e_PRIM_x
Graph_data$Score_type <- "Competitiveness Score"
Graph_data$`Competitiveness Score` <- round(Graph_data$Value, 2)
title1 <-paste("Competitiveness\nby",paste0(country_interest),"Subsector")
mycol <-c("red", "yellow", "#006600")
ggplot(data = Graph_data, aes(x = Score_type, y = reorder(Primary,Value), fill=Value)) +
geom_tile(aes(fill = Value), colour= "white")+
geom_text(data=Graph_data,aes(y=Primary, x= Score_type, label=Value))+
labs(title =(paste0(title1)),y = "", x = "")+
scale_fill_gradientn(colours = mycol)+
theme(legend.title=element_blank())+
theme(legend.position="bottom")
})
}
shinyApp(ui, server)

shinyapps.io does not draw plots

I built a simple app using FactorMineR package to do MCA analysis and clustering depending on selected variables.
The app works fine on my local device, however it does not show any plots (either base plots and ggplots) on shinyapps.io server. I checked the packages and locally and remotley they are the same. I also checked if the MCA() function from FactoMineR pcg even works by extracking some results and rendering them as a table what gave positive results. So there is only the problem with plots drawing. I have been trying to solve it for two days but nothing helps so I am asking you for any advice.
Here is how it looks locally:
Here is the link to the app: https://mikolajm.shinyapps.io/MCA_test/
And a reproducible example
library(shiny)
library(FactoMineR)
library(cluster)
library(ggplot2)
data(tea)
ui <- fluidPage(
# Application title
titlePanel("MCA"),
textOutput("packages"),br(),
tableOutput("table"),br(),
fluidRow(
column(4, checkboxGroupInput("Variables", "Select variables:",
names(tea), selected=c("breakfast", "tea.time"))),
column(4, plotOutput("plot")), column(4, plotOutput("plot1"))),
fluidRow(column(12, plotOutput("dendro", height = "700px", width="1200px"))
)
)
server <- function(input, output) {
## packages checking
output$packages <- renderText({.packages()})
tea_selected <- reactive({
tea[, input$Variables]
})
## table with some results from MCA() fun
output$table <- renderTable({
tea.mca <- MCA(tea_selected(), ncp=9)
tea.mca$eig[1:5,]
})
## mca1
output$plot <- renderPlot({
library(FactoMineR)
par(mfrow=c(2,2))
tea.mca <- MCA(tea_selected(), ncp=9)
})
## mca with ggplot
output$plot1 <- renderPlot({
tea.mca <- MCA(tea_selected(), ncp=9)
tea_vars_df <- data.frame(tea.mca$var$eta2, Variable =names(tea_selected()))
library(ggplot2)
pp <- ggplot(data=tea_vars_df, aes(x=Dim.1, y=Dim.2, label=Variable))+
geom_hline(yintercept = 0, colour = "gray70") +
geom_vline(xintercept = 0, colour = "gray70") +
geom_point()+
geom_text() +
ggtitle("MCA plot of variables ")+
theme_bw()
pp
})
### dendro
output$dendro <- renderPlot({
library(FactoMineR)
library(cluster)
tea.mca <- MCA(tea_selected(), ncp=9)
classif <- agnes(tea.mca$ind$coord,method="ward")
plot(classif,main="Dendrogram",ask=F,which.plots=2)
})
}
# Run the application
shinyApp(ui = ui, server = server)
EDIT: You can see plots obviously, but
ORIGINAL
I could not see plots in your shiny app when I ran your code.
After some digging, my guess is only that:
You use a lot of functions that come with the FactoMineR package. For instance, you use the function MCA in output$plot1 code block. Type MCA in your R command line, and it should print the function. You can see MCA does a lot of stuff and eventually calls plot.MCA. Now type plot.MCA in your R command line. You can see that plot.MCA has a lot of plot commands, and I'm pretty sure this executes all the plotting when you call MCA. I think your problem is that plot in the function plot.MCA is sent to the graphic device, and these plots are not saved, ie they are not return() to the parent environment. This is only speculation.

Get row number from of data point from event_data

I have been creating a data viewer app using shiny and plotly. I want to make a create a multi dimensional scaling view of my data, and then click on a data point to be able to view the individual point as a barplot. I was inspired by this example.
Here is a minimal almost working example:
The ui.r file
library(shiny)
library(mlbench)
library(plotly)
library(shinythemes)
library(dplyr)
# Load the data
allDat <- iris[,-5]
# ui.R definition
ui <- fluidPage(
# Set theme
theme = shinytheme("spacelab"),
# Some help text
h2("Inspect each element in iris data set"),
h4("This a shiny app exploiting coupled events in plotly"),
tags$ol(
tags$li("The first chart showcases", tags$code("plotly_click"))
),
# Vertical space
tags$hr(),
# First row
fixedRow(
column(6, plotlyOutput("Plot1", height = "600px")),
column(6, plotlyOutput("Plot2", height = "600px"))),
tags$hr())
The server.r file
# server.R definition
server <- function(input, output){
d <- dist(allDat) # euclidean distances between the rows
fit <- cmdscale(d,eig=TRUE, k=2) # k is the number of dim
# plot solution
x <- fit$points[,1]
y <- fit$points[,2]
plot.df <- data.frame(x=x,y=y,allDat)
output$Plot1 <- renderPlotly({
plot_ly(plot.df, x = x, y = y, mode="markers", source = "mds") %>%
layout(title = "MDS of iris data",
plot_bgcolor = "6A446F")
})
# Coupled event 2
output$Plot2 <- renderPlotly({
# Try to get the mouse click data
event.data <- event_data("plotly_click", source = "mds")
# If NULL dont do anything
if(is.null(event.data) == T) return(NULL)
# I need the row of the data in the allDat data frame
# pretty sure this is not correct
ind <- as.numeric(event.data[2])
p1 <- plot_ly(x = colnames(allDat), y=as.numeric(allDat[ind,]),type="bar")
})
}
To run this, put these two files in a folder called something, e.g. dataViewer, then run runApp("dataViewer") from the directory that contains the dataViewer folder.
What is the question and what am I seeking?
I do not understand the output that comes from the event_data function. I want to be able to click on a point on the scatter plot and extract the row number of that data point from the allDat data frame, or the plot.df data frame, because it should be the same. Then I want to use that row number to further visualize that specific point in the barplot on the right.
I looked into the event.data object, and think the value you are looking for is event.data$pointNumber (which starts with 0 so you need to use event.data$pointNumber + 1 to identify the line).
event.data is a list with four names: curveNumber, pointNumber, x and y.

Many error signs when running ggplot in render plot (shiny in general)

Took very basic shiny scripts and were able to play around the generic data sets. When I tried to put in my own and run ggplot, I've come across several errors. Most recent is what appears in my main panel of shiny app and console in Rstudio
...
"ggplot2 doesn't know how to deal with data of class reactive"
...
In general, I stripped down my ggplot to the most basic elements and still not sure from where ggplot is calling data while in shiny. I am guessing the reactive function, but honestly, I am lost.
Below are scripts
_____ui.R________
shinyUI(pageWithSidebar(
headerPanel('Mock Risk Scorecard'),
sidebarPanel(
selectInput('xcol', 'X Axis', names(RandomRiskCard)),
selectInput('ycol', 'Y Axis', names(RandomRiskCard),
selected=names(RandomRiskCard)[[2]]),
min = 1, max = 9),
mainPanel(
plotOutput('plot1')
)
)
)
_____server.R____
palette(c("#E41A1C", "#377EB8"))
shinyServer(function(input, output, session) {
# Combine the selected variables into a new data frame
selectedData <- reactive({
RandomRiskCard[, c(RandomRiskCard$xcol, RandomRiskCard$ycol)]
})
output$plot1 <- renderPlot({
p <- ggplot(selectedData, aes(x = RandomRiskCard$xcol, y = RandomRiskCard$ycol))
p <- p + geom_point()
})
})
I also loaded up my data and Run Shiny in different script windows as follow
install.packages("shiny")
library(shiny)
library(ggplot2)
runApp("U:/App-1")
as well as
RandomRiskCard = read.csv("U:/App-1/RandomRiskCard.csv")
I am eventually hoping to incorporate factor function and annotate with colors like I had done with my original ggplot. If it wasn't already obvious I am a newbie at this, but shiny has me completely twisted.
Reactive expressions should be called in the same way as parameter-less functions, with following parentheses: ggplot(selectedData(),...
xcol and ycol should be obtained via input:
p <- ggplot(selectedData(), aes(x = input$xcol, y = input$ycol)) in output$plot, and
RandomRiskCard[, c(input$xcol, input$ycol)] in selectedData

Resources