Change plot axis values dynamically from dataframe in Shiny - r

I'm using Rstudio and Shiny for the project.
I have defined a variable res and it contains dataframe with multiple rows and columns, then I make a plot and its x y and color are the data from res dataframe.
My problem is that when i Run it, if I write that i want x axis to be inputted variable values (input$SelInp), I dont get dataframe values, instead, I get only column name.
if I change the code to get the values directly from dataframe (res$some_column_name) I get the correct values.
ui.R
selectInput("SelInp",
label = "Choose one:",
choices = colnames(res)
)
server.R
output$plt = renderPlot({
qplot(data = res,
x = input$SelInp, #this only returns a column name
y = res$loan_amnt, # this returns correct values from column loan_amt
ylab = "some y axis",
xlab = "some x axis",
main="Our Chart")
}
)
so, I want to get the values in input$SelInp thanks in advance

I think the reason is that the selectInput is returning the column name as a character. qplot is expecting a variable. I didn't check if qplot has an option to use characters to specify scales but aes_string in ggplot does that:
ui.R
library(shiny)
library(ggplot2)
shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(sidebarPanel(
selectInput(
"selectedCol",
"Select colum for X axis",
choices = colnames(mtcars),
selected = colnames(mtcars)[1]
)
),
mainPanel(plotOutput("distPlot")))
))
server.R
library(shiny)
library(ggplot2)
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
x_axis <- input$selectedCol
gg <-
ggplot(mtcars, aes_string(x = x_axis, y = "hp", color = "cyl"))
gg <- gg + geom_point()
gg
})
})
Let me know if this helps.

Related

accessing the selected value from filter_select or sharedData object crosstalk R

I want to be able to use the selected value from a crosstalk::filter_select in the title of a plot that is based on the sharedData. Here is a minimal example of what I am after (except instead of "x" in the title it is the filtered value).
library(crosstalk)
library(ggplot2)
library(plotly)
shared_mtcars <- SharedData$new(mtcars)
plt <- ggplot(shared_mtcars, aes(wt, mpg))+
geom_point()+
labs(title=paste("Weight vs. MPG for", "x", "cylinder cars."))
bscols(widths = c(3,NA),
list(
crosstalk::filter_select("cyl", "Cylinders", shared_mtcars, ~cyl, multiple = FALSE)
),
ggplotly(plt)
)

SelectInput to change multiple elements in Shiny

Is there a way to have a selectInput change two elements of a plot? For example below, I created a reactive block to manipulate the data I want to plot in geom_point for each selectInput choice and it works perfectly. However, I also want the color of the points to change, a different color for each choice that is automatic, the user need not choose one themselves. So for one input$case points I want what is written in geom_point "orangered2". But if they choose the other input$case option, I would like the points in geom_point to be "gold".
Maybe an if statement but I am not sure where to nest that if so.
I posted a snippet of my UI and server bits.
UI snippet from a tab
tabPanel("Analysis",
sidebarLayout(
sidebarPanel(width = 4,
selectInput(inputId = "case",
label="Locations",
choices = c("TRUE", "FALSE")))
Server snippet
server <- function(input, output){
data_use <- reactive({
real_final[real_final$case %in% input$case,]
})
output$bathy <- renderPlot({
autoplot.bathy(shelf, geom=c("raster", "contour")) +
scale_fill_gradientn(name = "meters above\nsea level", colours = c("plum2", "steelblue4","steelblue3", "steelblue2", "steelblue1"),
breaks = c(-6000,0),
limits = c(-6000,0),
labels = c("-6000m","0m"),
na.value = "black") +
geom_point(data = data_use(), aes(long, lat), color = "orangered2", pch = ".") +
xlab("Longitude") +
ylab("Latitude") +
ggtitle("Seal Locations") +
theme(axis.text.x=element_text(size=6),
axis.text.y=element_text(size=6),
axis.title=element_text(size=10,face="bold"))
An option is to return a list with a reactive conductor:
data_and_color <- reactive({
list(
data = real_final[real_final$case %in% input$case,],
color = ifelse(input$case == "TRUE", "gold", "orangered2")
)
})
Then in the renderPlot:
x <- data_and_color()
ggplot(data = x$data, ......)
color = x$color

Problem passing variable names via selectInput() in R/Shiny

I'm building a shinyapp where I am passing variable names as arguments to the server with the selectInput() widget. The following static example illustrates the plot that I want displayed:
g <- ggplot(d, aes(y, fill = var1, colour = var1)) +
geom_density(alpha=.2)
Just to be clear, here is an image of the above plot
What I want to do in my shinyapp is to separate the plotted distributions by different variables that the user can choose via selectInput(). But when I substitute var1 in the above with a generic argument, this is not what I get. Please see the example:
library(ggplot2)
library(shiny)
d <- data.frame(var1=as.factor(sample(x = 1:4, size = 250, replace = TRUE)),
var2=as.factor(sample(x = 1:4, size = 250, replace = TRUE)),
y=rnorm(250, mean = 0, sd = 1))
nms <- names(d)
ui <- fluidPage(selectInput(inputId ="var", "Variable:",
choices = nms, selected = "var1"),
plotOutput(outputId = "plot")
)
server <- function(input, output) {
g <- ggplot(d, aes(y, fill = input$var, colour = input$var)) +
geom_density(alpha=.2)
output$plot <- renderPlot(g)
}
shinyApp(ui,server)
The actual output I get is
different from the static example I started with (click through for image).
Can someone please point out my error? Thankful for help.
input$var is a string. Therefore, do
output$plot <- renderPlot({
g <- ggplot(d, aes_string("y", fill = input$var, colour = input$var)) +
geom_density(alpha=.2)
g
})

R Shiny: error when interactive input goes into a ggplot from rds file (Error in eval: object 'x' not found)

I want to produce an application using R's shiny package. I would like to upload ggplots from another project and add some interactive content.
When I add a data point using geom_point() to a ggplot that was created in the same R code this works fine. However, when I save and re-read the ggplot again (*), an error occurs. I could still add the geom_point (**), but it does not accept the interactive content from input$slider.
ui.R
library(shiny)
shinyUI(
fluidPage(
# Title
titlePanel(""),
# sidebar
sidebarLayout(
sidebarPanel("",
sliderInput("slider", "slider",
min = 100, max = 500, value = 300, step = 10)
),
# Main
mainPanel("",
plotOutput("ggplt")
)
)
)
)
server.R
library(shiny)
shinyServer(
function(input, output){
# produce a plot
output$ggplt <- renderPlot({
# ggplot scatterplot
library(ggplot2)
gg <- ggplot(data = mtcars, aes(x = disp, y = mpg)) +
geom_point()
# (*) save ggplot
#saveRDS(gg, "plt.rds")
#rm(gg)
#gg <- readRDS("plt.rds")
# x-coordinate for geom_point
xc <- as.numeric(input$slider)
gg + geom_point(aes(x = xc, y = 20), size = 5, colour = "red")
## (**) alternative
#gg + geom_point(aes(x = 400, y = 20), size = 5, colour = "red")
})
}
)
I don't really know what is going on here, and I think it is probably some subtle interaction between the ggplot2 environment handling and the shiny reactive environment handling. It might be worth flagging as a bug.
However there are a number of ways to make it work with small changes. I think the best is to use a reactive function for the slider value, although just assigning xc with the frowned upon <<- also seems to work and is a smaller change.
You could also just use input$slider directly in the aes(..) function as that seems to work too, but using a reactive function feels cleaner.
So this is what I suggest as a workaround:
library(shiny)
library(ggplot2)
u <- shinyUI(
fluidPage(
titlePanel(""),
sidebarLayout(
sidebarPanel("", sliderInput("slider", "slider",
min = 100, max = 500, value = 300, step = 10)
),
mainPanel("", plotOutput("ggplt")
)
)))
s <- shinyServer( function(input, output){
sliderval <- reactive({input$slider})
output$ggplt <- renderPlot({
req(input$slider)
gg <- ggplot(data = mtcars) +
geom_point(aes(x = disp, y = mpg))
# (*) save ggplot
saveRDS(gg, "plt.rds")
rm(gg)
gg <- readRDS("plt.rds")
gg + geom_point(aes(x = sliderval(), y = 20), size = 5, colour = "red")
})
})
shinyApp(u,s)
yielding:

geom_text in Choropleth map (ggplot2)

I'm working with choropleth map (ggplot2), i have problem implementing geom_text properly. In output it is showing text over map but i can see many repeated name, no idea why, and need help to fix that please. Using R studio, Australia map shape file and data in a csv file. Moreover I had intention to show values over map instead of state names, don't know how.
codes in UI.R file
library(shiny)
# Define UI for application
shinyUI(fluidPage(
# Application title
headerPanel("Unemployment rate Data"),
# Sidebar with controls to select the variable to plot against
# specify whether outliers should be included
sidebarLayout(
sidebarPanel(
selectInput("variable", "Type:",
c("States" = "region",
"Unemployment_Rate" = "unemployment_rate_2015"
)
)
#checkboxInput("outliers", "Show outliers", FALSE)
),
# Show the caption and plot of the requested variable against population data data
mainPanel(
h3(textOutput("caption")),
plotOutput("datPlot")
)
)#----/sidebar layout
))#----/shinyUI
codes in Server.R file
require(maptools)
require(ggmap)
require(maps)
require(mapproj)
require(data.table)
library(rgeos)
library(plyr)
library(shiny)
library(datasets)
library(ggplot2) # load ggplot
setwd("C:/Users/AbdullahAl/Documents/AU-Shapefile")
pop <- read.csv("unemployment.csv")
AUS = readShapeSpatial("AUS_adm1")
shinyServer(function(input, output) {
# Compute the forumla text in a reactive expression since it is
# shared by the output$caption and output$mpgPlot expressions
output$caption <- reactiveText(function(){
paste("States ~", input$variable)
})
# ggplot version
output$datPlot <- reactivePlot(function() {
pop <- data.table(States = pop$region, var = factor(pop[[input$variable]]))
# Generate a plot of the requested variable against year and only
# include outliers if requested
AUS <- fortify(AUS, region = "NAME_1")
#add color="black" inside geom_map to have the boarder black
ggplot() + geom_map(data = pop, aes(map_id = States, fill = var), map = AUS) +
expand_limits(x = AUS$long, y = AUS$lat) +
# to add values over
geom_text(data = AUS, aes(x =long , y = lat, label = id, size = 2.5),
check_overlap = TRUE, position = "jitter", parse = FALSE) +
geom_label()
# facet_wrap( ~ var) - use this to show each divided states
})
})
Link for .csv file
https://onedrive.live.com/redir?resid=15945AE760E741A4!2712&authkey=!AChRc_Cl_PjJ_I4&ithint=file%2ccsv
And the output as image
the image is showing Australis's map and repeated name of the states over it

Resources