Get row number from of data point from event_data - r

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.

Related

numericInput to data frame in Shiny

Sorry if this question has been asked before, but I haven't quite found exactly what I was looking for by searching around.
I'm working on a small app to bring in scores from a debate activity and have those scores plotted in a scatterplot. I've figured out how to actually make the plot, but getting the data into it is a separate story.
I have all of my inputs as a numericInput with a unique input ID, but I haven't had any luck putting that data into its own frame.
I tried making a few different sets and then compiling all of those into one frame (using name1<-c(x, y z), name2<-c(a,b,c)... and then frame<-as.matrix(c(name1,name2....)) but it tells me that I'm attempting to do something that requires a reactive context.
If anyone knows how I could make my numericInputs drop into a dataframe, that would be lovely.
EDIT: I think I'm looking to make a reactive data table, but I'm not entirely sure. Again, any suggestions will be greatly appreciated!
Given the description of your problem, which is not that clear and do not show exactly what you need, this is what I recomment:
An app which takes 6 numerics inputs, combine all in a data frame with two columns and create a scatter plot with that data.
library(shiny)
library(ggplot2)
library(dplyr)
# 1 - The UI with a sidebar layuot
ui <- fluidPage(
sidebarLayout(
# A well panell to separate the values
# for the X axis
sidebarPanel = sidebarPanel(
wellPanel(
h3("X axis"),
numericInput('numb1', 'A', value = 1),
numericInput('numb2', 'B', value = 2),
numericInput('numb3', 'C', value = 3)
),
# A well panell to separate the values
# for the Y axis
wellPanel(
h3("Y axis"),
numericInput('numb4', 'A', value = 1),
numericInput('numb5', 'B', value = 2),
numericInput('numb6', 'C', value = 3)
)),
# Main panel with the plot
mainPanel = mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output, session) {
# Here You create a reactive objece with all the values
data <- reactive({
data.frame(
a = c(input$numb1, input$numb2, input$numb3),
b = c(input$numb4, input$numb5, input$numb6)
)
})
# plot output
output$plot <- renderPlot({
data() %>%
ggplot(aes(x = a, y = b)) +
geom_point()
})
}
shinyApp(ui, server)
Let me know if this is it

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)

Removing the X,Y in nearPoints() Output

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)

How to Order ggplot2 x-axis dates chronologically when in mm-yyyy format?

I'm designing an R program to output different graphs of any csv file input. I am using Rstudio Shiny and ggplot2 to develop the program.
My problem involves ordering dates chronologically rather than alphabetically (which is the default apparently). Let's use this code as an example (my code is a bit different, but this is code from someone who helped me earlier):
related posts:
Unable to change the graph form of my ggplot rshiny program, help me find the bug?
Sorting months in R
How do you order a nominale variable. e.g month in R?
Boxplot with ggplot2 in R - returns by month
server.R
library(shiny)
library(datasets)
library(ggplot2)
X <- read.csv(file.choose())
# Define server logic required to summarize and view the selected dataset
shinyServer(function(input, output) {
output$opt.x <- renderUI({
selectInput("xcolumn", "X column to Plot",
names(Y())
)
})
output$opt.y <- renderUI({
selectInput("ycolumn", "Y Column",
names(Y()))
})
# Generate a summary of the dataset
output$summary <- renderPrint({
dataset <- X
summary(dataset)
})
# Show the first "n" observations
output$view <- renderTable({
head(X, n = input$obs)
})
createPlot <- function(df, colx, coly) {
p <- ggplot(data=df, aes(x=df[,colx],y=df[,coly]), environment = environment()) #+ geom_line(aes(x=df[,colx],y=df[,coly], group=colx))
p <- p + geom_line(aes(group=colx))
p <- p + xlab(names(df)[colx]) + ylab(names(df)[coly])
}
Y <- reactive({
X
})
# create a basic plot
output$plotBasic <- reactivePlot(function() {
df <- Y()
print(createPlot(df, colx=input$xcolumn, coly=input$ycolumn))
})
})
ui.R
library(shiny)
# Define UI for dataset viewer application
shinyUI(pageWithSidebar(
# Application title
headerPanel("My app!"),
# Sidebar with controls to select a dataset and specify the number
# of observations to view
sidebarPanel(
numericInput("obs", "Number of observations to view:", 13),
uiOutput("opt.x"), #dynamic UI
uiOutput("opt.y") #value comes from Server.R
),
# Show a summary of the dataset and an HTML table with the requested
# number of observations
mainPanel(
tabsetPanel(
tabPanel("Table", tableOutput("view")),
tabPanel("BasicGraph", plotOutput("plotBasic"))
)
)
))
This can be taken care of easily with factor or as.Date functions if you started with a list that you knew of, but here I am taking in input (can assume the format is mm-yyyy) and I do not know how to set the column of x variable data to a variable. This is because the user can choose any column in the imported data as the X column.

Resources