Related
I'm pretty new to r and shiny and I am currently working on my first personal project. My project is about Pokemon and I am currently having trouble creating an interactive radar chart. I have tried looking at other questions about on this website about r and radar charts but couldn't really find the right answer since the dataset was usually in a different format, and the answers didn't provide a way to do it interactively.
What I'm trying to achieve: Create an interactive radar chart where the user can select a Pokemon and the radar chart will display that Pokemon's base stats (hp, attack, defense, etc.)
dataset:
name hp defense attack sp_attack sp_defense speed
1 Bulbasaur 45 49 49 65 65 45
2 Ivysaur 60 63 62 80 80 60
3 Venusaur 80 123 100 122 120 80
4 Charmander 39 43 52 60 50 65
5 Charmeleon 58 58 64 80 65 80
6 Charizard 78 78 104 159 115 100
...
ui.R:
library(shiny)
library(plotly)
ui <- navbarPage(title = "Pokemon Research",
tabPanel(title = "Types and Stats",
sidebarPanel(
selectInput(inputId = "diff_stat",
label = "Different Types and their Base Statistics",
choices = c("hp", "attack", "defense", "special_attack",
"special_defense", "speed", "total"))
),
mainPanel(plotlyOutput("type"))),
tabPanel(title = "Pokemon Statistics",
sidebarPanel(
selectInput(inputId = "indv",
label = "Pokemon",
choices = data$name
),
#IDK WHAT TO PUT HERE FOR THE MAINPANEL
)))
server.R:
library("shiny")
library("ggplot2")
data <- read.csv("../data/pokemon.csv", stringsAsFactors = FALSE)
type_data <- data %>%
select(name, type1, hp, defense, attack, sp_attack, sp_defense, speed) %>%
group_by(type1) %>%
summarise(hp = mean(hp),
attack = mean(attack),
defense = mean(defense),
special_attack = mean(sp_attack),
special_defense = mean(sp_defense),
speed = mean(speed),
total = mean(attack + defense + hp + sp_attack + sp_defense + speed))
indv_data <- data %>%
select(name, hp, defense, attack, sp_attack, sp_defense, speed)
server <- function(input, output) {
output$type <- renderPlotly({
ggplot(data = type_data, mapping = aes_string(x = "type1", y = input$diff_stat)) +
geom_line(group = 1) +
geom_point() +
labs(x = "Types",
y = "Base Stat (avg)")
})
output$radar <- renderPlot({
#WHAT DO I PUT HERE TO MAKE THE RADAR CHART
})
}
Any help is greatly appreciated!
This can help. I only included the code for the radar chart.
library(tidyverse)
library(shiny)
library(plotly)
pokemons <-
read_table('
name hp defense attack sp_attack sp_defense speed
Bulbasaur 45 49 49 65 65 45
Ivysaur 60 63 62 80 80 60
Venusaur 80 123 100 122 120 80
Charmander 39 43 52 60 50 65
Charmeleon 58 58 64 80 65 80
Charizard 78 78 104 159 115 100')
ui <- navbarPage(title = "Pokemon Research",
tabPanel(title = "Pokemon Statistics",
sidebarPanel(
selectInput(inputId = "indv",
label = "Pokemon",
choices = pokemons$name,
selected = 'Bulbasaur')
),
mainPanel(
plotlyOutput('radar') #the radar plot
)
))
server <- function(input, output, session) {
output$radar <- renderPlotly({
pkmn <- filter(pokemons, name == input$indv)
r <- map_dbl(pkmn[, 2:6], ~.x)
nms <- names(r)
#code to plot the radar
fig <- plot_ly(
type = 'scatterpolar',
r = r,
theta = nms,
fill = 'toself',
mode = 'markers'
)
fig <- fig %>%
layout(
polar = list(
radialaxis = list(
visible = T,
range = c(0,max(r))
)
),
showlegend = F
)
})
}
shinyApp(ui, server)
I'm trying to create a ggplot that is rendered as per the 3 user input's which should be dependent of each other.
My data Set looks like this :
Week Region Movement_Type Warehouse f_TAT Quantity
April 05 - April 11 North Local ABC In TAT 10
April 05 - April 11 North Local ABC Out TAT 5
April 05 - April 11 East Local ABC In TAT 13
April 05 - April 11 East Local ABC Out TAT 6
March 01 - March 07 West Inter-State XYZ In TAT 15
March 01 - March 07 West Inter-State XYZ Out TAT 10
What i have been able to achieve as of now:
I have been able to create the ggplot with 3 filter which as of now are not dependent of each other. When no particular filter is selected it shows the option of All as default. But it is plotting wrong plot
When I select the warehouse filter and region filter the data seems to change but is still displaying wrong plot .
My code that helped me achieve this :
library(plotly)
library(ggplot2)
library(dplyr)
library(reshape2)
library(gtools)
ui <- shinyUI(
navbarPage(
title = 'Dashboard',
tabPanel('Performance',
tabsetPanel(
tabPanel('Tab1',
fluidRow(
column(3,selectInput('warehouse', 'Select Warehouse', c("All",as.character(unique(plot1$Warehouse))))),
column(3,selectInput('region', 'Select Region', c("All",as.character(unique(plot1$Region))))),
column(3,selectInput('mov_type', 'Select Movement Type', c("All",as.character(unique(plot1$Movement_Type))))),
column(12,plotlyOutput("myplot_fwd_f"))
)
)
)),
tabPanel('Orders',
fluidRow(
)
)
)
)
server <- function(input, output) {
data1 <- reactive({
plot1 <- read.csv("plot1.csv", sep = ",", header = TRUE)
temp <- plot1
if (input$warehouse != "All"){
temp <- temp[temp$Warehouse == input$warehouse,]
}
if (input$region != "All"){
temp <- temp[temp$Region == input$region,]
}
if (input$mov_type != "All"){
temp <- temp[temp$Movement_Type == input$mov_type,]
}
return(temp)
})
output$myplot_fwd_f <- renderPlotly({
data <- data1()
p<- ggplot(data, aes(fill=f_TAT, y=Quantity , x=reorder(Week, + Week))) +
geom_bar(position="fill", stat="identity",colour="black") + scale_fill_manual(values=c("#44E62F", "#EC7038")) +
labs(x = "Week") +
labs(y = "Percentage") +
labs(title = "") +
scale_y_continuous(labels=scales::percent) +
geom_text(data = . %>%
group_by(Warehouse,Region,Movement_Type,Week) %>%
mutate(p = Quantity / sum(Quantity )) %>%
ungroup(),
aes(y = p, label = scales::percent(p)),
position = position_stack(vjust = 0.5),
show.legend = FALSE) +
theme(axis.text.x = element_text(angle = 10))
p <- ggplotly(p, tooltip="text")
p
})
}
shinyApp(ui, server)
I want to know if there is a way to make the 3 filters dependent of each other ? As as of now they display all the unique values they can find in the particular column of the data base.
When by default all three filters have "All" option selected in them they seems to be plotting all the possible combinations on the plot, how can this be corrected.
And lastly can I change the 3rd "Movement Type" filter into a Multi Check-Box option filter?
Thank you.
Edit : Thank you so much #YBS i was able to achieve the dependent filter's all thanks to you .. #YBS as per stated in your comment below it is showing multiple % for In TAT/ Out Tat Reason being there are multiple values for In/Out TAT for a particular week. Can we try to show the overall percentage of a week instead of multiple In TAT/ Out TAT % ? That would solve my last remaining problem. Thank you again for your help.
Edit 2 : Hi YBS thank you for the Update. The final Output looks like this now.
It seems it is still dividing it into different level's, is there a way to show only one % of In/Out TAT for a week. One thing I also noticed that The 3rd filter when only one filter is selected instead of all it show's this error "Error : object of type 'closure' is not subsettable", Even when there is a data set for the filter applied. Do i need to expand the data set for your better understanding ?
You need to use updateSelectInput() to update the values of the subsequent selectInputs. Then you need to group_by only Week. To aggregate per week some data processing is required. Perhaps this meets your need.
df <- read.table(text=
"Week, Region, Movement_Type, Warehouse, f_TAT, Quantity
April 05 - April 11, North, Local, ABC, In TAT, 10
April 05 - April 11, North, Local, ABC, Out TAT, 5
April 05 - April 11, East, Local, ABC, In TAT, 13
April 05 - April 11, East, Local, ABC, Out TAT, 6
March 01 - March 07, West, Inter-State, XYZ, In TAT, 15
March 01 - March 07, West, Inter-State, XYZ, Out TAT, 10", header=TRUE, sep=",")
library(plotly)
library(ggplot2)
library(dplyr)
library(reshape2)
library(gtools)
plot1 <- df
ui <- shinyUI(
navbarPage(
title = 'Dashboard',
tabPanel('Performance',
tabsetPanel(
tabPanel('Tab1',
fluidRow(
column(3,selectInput('warehouse', 'Select Warehouse', c("All",as.character(unique(plot1$Warehouse))))),
column(3,selectInput('region', 'Select Region', c("All",as.character(unique(plot1$Region))))),
column(3,checkboxGroupInput("mov_type","Select Movement Type", inline = TRUE, choices = c("All",unique(plot1$Movement_Type)))),
#column(3,selectInput('mov_type', 'Select Movement Type', c("All",as.character(unique(plot1$Movement_Type))))),
column(12,plotlyOutput("myplot_fwd_f"))
)
)
)),
tabPanel('Orders',
fluidRow( DTOutput("t1")
)
)
)
)
server <- function(input, output, session) {
data1 <- reactive({
plot1 <- df # read.csv("plot1.csv", sep = ",", header = TRUE)
temp <- plot1
if (input$warehouse != "All"){
temp <- temp[temp$Warehouse == input$warehouse,]
}
return(temp)
})
observeEvent(input$warehouse, {
df1 <- data1()
updateSelectInput(session,"region",choices=c("All",as.character(unique(df1$Region))))
})
data2 <- reactive({
req(input$region)
plot1 <- data1()
temp <- plot1
if (input$region != "All"){
temp <- temp[temp$Region == input$region,]
}
tmp <- temp %>%
group_by(Week) %>%
mutate(p = Quantity / sum(Quantity )) %>%
ungroup()
return(tmp)
})
observeEvent(input$region, {
df2 <- req(data2())
#updateSelectInput(session,"mov_type",choices=c("All",unique(df2$Movement_Type)) )
updateCheckboxGroupInput(session,"mov_type",choices=c("All",as.character(unique(df2$Movement_Type))), inline=TRUE, selected="All")
})
data3 <- reactive({
req(input$mov_type)
if ("All" %in% input$mov_type){
data <- data2()
}else{
data <- data2()[data2()$Movement_Type %in% input$mov_type,]
}
tmp <- data %>%
group_by(Week,f_TAT) %>%
mutate(Quantity = sum(Quantity)) %>% distinct(Week,f_TAT,Quantity) %>%
group_by(Week) %>%
mutate(p = Quantity / sum(Quantity )) %>%
ungroup()
return(tmp)
})
output$t1 <- renderDT(data3())
output$myplot_fwd_f <- renderPlotly({
data <- req(data3())
p<- ggplot(data, aes(fill=f_TAT, y=p , x=Week)) +
geom_bar(position="fill", stat="identity",colour="black") + scale_fill_manual(values=c("#44E62F", "#EC7038")) +
labs(x = "Week") +
labs(y = "Percentage") +
labs(title = "") +
scale_y_continuous(labels=scales::percent) +
geom_text(aes(y = p, label = scales::percent(p)),
position = position_stack(vjust = 0.5),
show.legend = FALSE) +
theme(axis.text.x = element_text(angle = 10))
p <- ggplotly(p) #, tooltip="text")
p
})
}
shinyApp(ui, server)
I am trying to create a dashboard using R Shiny from NYC Tree Census 2015. The dashboard should look something like in the picture here > Dashboard in Shiny Picture
My code is mentioned below:
library(shiny)
library(tidyverse)
library(ggplot2)
my_data <- read.csv("/Users/abhikpaul/Documents/Documents/Github/Fiverr/2015_Street_Tree_Census_-_Tree_Data.csv")
ui <- fluidPage(
titlePanel("The Dashboard of Tree Distribution in New York City"),
sidebarLayout(
sidebarPanel(
# Description ----
helpText("In this page you can get information about the tree distribution, status, health conditions, and species rank in New York City. Please choose the borough that you want to check. It may take 10 seconds for the graphics to load. Thank you for your patience!"),
#Input: Check boxes for Boroughs ----
checkboxGroupInput("checkboxInput",
label = "Borough",
choices = list("Bronx",
"Brooklyn",
"Manhattan",
"Queens",
"Staten Island"),
selected = "Bronx"),
),
# Main panel for displaying outputs ----
mainPanel(
# Tabs panel for displaying outputs ----
tabsetPanel(type = "tabs",
#Output: About ----
tabPanel("About",
h3("About this dataset", align = "left"),
p("The dataset displays the information of trees (including health, status, species, etc.) within the five boroughs in New York City. The dataset is organized by NYC parks & Recreation and partner organizations."),
h3("How to make NYC an urban forest?", align = "left"),
p("As a group, we are concerned about planting tree and green environments. Therefore, we will focus on identifying the locations that require more taking care of trees, the top species that have the most number of trees in each borough, the health conditions of those species, and the distribution of trees in each borough."),
HTML("<p>For more information, visit: <a href='https://data.cityofnewyork.us/Environment/2015-Street-Tree-Census-Tree-Data/uvpi-gqnh'>2015 NYC Tree Census</a></p>")
),
#Output: Status ----
tabPanel("Status", plotOutput(outputId = "statusplot")),
)
)
)
)
)
server <- function(input, output) {
my_data <- as_tibble(my_data)
my_data <- my_data[my_data$borough %in% checkboxInput,]
my_data <- data.frame(table(my_data$borough,my_data$status))
my_data <- my_data[apply(my_data!=0, 1, all),]
my_data <- my_data %>%
group_by(Var1) %>%
mutate(Percent = (Freq/sum(Freq) * 100))
output$statusplot <- renderPlot({
ggplot(my_data, aes(fill = Var2, y = Percent, x = Var1)) +
geom_bar(position = "dodge", stat = "identity")
})
}
shinyApp(ui = ui, server = server)
However, while running the app, I am getting an error as mentioned below
Warning: Error in match: 'match' requires vector arguments 50: %in% 47: server [/Users/abhikpaul/Documents/Documents/GitHub/Fiverr/my_app.R#90]Error in match(x, table, nomatch = 0L) : 'match' requires vector arguments
Can someone help me fix this issue as I am a newbie in R Shiny?
Try this
server <- function(input, output) {
output$statusplot <- renderPlot({
my_data <- as_tibble(my_data)
my_data <- my_data[my_data$borough %in% input$checkboxInput,]
my_data <- data.frame(table(my_data$borough,my_data$status))
my_data <- my_data[apply(my_data!=0, 1, all),]
my_data <- my_data %>%
group_by(Var1) %>%
mutate(Percent = (Freq/sum(Freq) * 100))
ggplot(my_data, aes(fill = Var2, y = Percent, x = Var1)) +
geom_bar(position = "dodge", stat = "identity")
})
}
I have a dataset with categorical and numeric variables.
My data looks like this
Region Country Project.ID Client PG Percent.of.CoE Status
1 Africa Sudan 1001 Vodafone PG 1 50 Signed
2 Europe Russia 1002 Vodafone Russia PG 2 50 Low
3 Europe United Kingdom 1003 Orange PG 3 50 Signed
4 Latin America Peru 1004 Co-operative Bank PG 3 50 Signed
5 Asia Malaysia 1005 AB Malaysia PG 2 14 Signed
6 Europe France 1006 Orange PG 4 50 High
7 Africa South Africa 1007 Coris Bank PG 1 40 Signed
8 Asia China 1008 Gulf Bank PG 2 50 Low
9 North America United States 1009 ABI PG 1 50 Signed
10 Europe Germany 1010 O2 PG 2 50 Medium
11 Latin America Argentina 1011 ACEP PG 3 40 Low
12 North America Canada 1012 BCN United States PG 1 100 Signed
The sample data is stored here
What am I trying to do with this data?
I want to create a simple app, which with filter categorical and numeric variables.
My current UI looks like this and this is my desired UI.
The first filter works perfectly. The second does not due to data structure.
Trying to resolve it, I changed tha data format, using gather, see the code below. As a result my data looks like this.
Percent.of.CoE variable value
1 50 Region Africa
2 50 Region Europe
23 40 Country Argentina
24 100 Country Canada
25 50 Client Vodafone
26 50 Client Vodafone Russia
47 40 PG PG 3
48 100 PG PG 1
49 50 Status Signed
50 50 Status Low
I am not sure that it is correct format for this. But any solution will work.
My code
library(shiny)
library(shinythemes)
library(tidyverse)
# Global code
# Read file on a local machine
data_pg <- read.csv("pg1.csv", header = TRUE, stringsAsFactors = FALSE)
# Transform into tidy data, removing long/lat variables.
data_pg_df3 <- data_pg %>% select(Region, Country, Client, PG, Status,
Percent.of.CoE) %>% gather(key = "variable", value = "value", -
c("Percent.of.CoE"))
# UI code
ui <- fluidPage(theme = shinytheme("united"),
titlePanel(h1("Test", align = "center")),
sidebarLayout(
sidebarPanel(
selectInput("dataInput", "Choose to filter by:",
choices = c("Region",
"Country",
"Client",
"PG",
"Status"),
selected = "Choose to display by"),
sliderInput("percentInput1", "Percent of CoE", min = 0,
max = 100, value = c(0, 0))
),
mainPanel(
# Output
tabsetPanel(type = "tabs",
tabPanel("Plot", plotOutput("plot", height = 850)))
)
)
)
# Server code
server <- function(input, output) {
# 1. Select among columns
selectedData <- reactive({
filter(data_pg_df3, variable == input$dataInput)
})
output$plot <- renderPlot({
ggplot(selectedData(), aes(x = value, fill = value)) + geom_bar(stat = "count") + theme(axis.title = element_blank())
})
HOW TO WRITE THE SECOND FILTER? I did. But wrong and might be wrong filtering too. But I think my dataframe is not good for this.
# # 2. Select among percents
# selectedPercent <- reactive({
# filter(data_pg_df3, Percent.of.CoE >= input$percentInput1[1] &
Percent.of.CoE <= input$percentInput1[2])
# })
#
# output$plot <- renderPlot({
# ggplot(selectedPercent(), aes(x = value, fill = value)) + geom_bar(stat = "count") + theme(axis.title = element_blank())
# })
}
shinyApp(ui = ui, server = server)
I want to filter by variable and then to filter by percent, leaving only projects withing selected range.
I don't think this has anything to do with your data structure. Try something like the following:
server <- function(input, output) {
# 1. Select among columns
filtered_data_1 <- reactive({
filter(data_pg_df3, variable == input$dataInput)
})
filtered_data_2 <- reactive({
filter(filtered_data_1(), Percent.of.CoE == input$percentInput1)
})
output$plot <- renderPlot({
ggplot(filtered_data_2(), aes(x = value, fill = value)) + geom_bar(stat = "count") + theme(axis.title = element_blank())
})
The key thing is to pass one reactive to another. Alternatively you could apply both filters within the same reactive:
server <- function(input, output) {
# 1. Select among columns
filtered_data <- reactive({
data_pg_df3 %>%
filter(variable == input$dataInput)
filter(Percent.of.CoE == input$percentInput1)
})
output$plot <- renderPlot({
ggplot(filtered_data(), aes(x = value, fill = value)) + geom_bar(stat = "count") + theme(axis.title = element_blank())
})
This can be done using your original data structure in a variety of ways. For example, you could just filter on Percent.of.CoE and then pass the column given by input$dataInput to your ggplot aesthetic.
I resolved also.
My server looks like this. In general, I was right and the answer above is correct too.
# Server
server <- function(input, output) {
# 1. Select among columns
selectedData <- reactive({
filter(data_pg_df3, variable == input$dataInput) %>%
filter(Percent.of.CoE >= input$percentInput1[1] & Percent.of.CoE <= input$percentInput1[2])
})
output$plot <- renderPlot({
ggplot(selectedData(), aes(x = value, fill = value)) + geom_bar(stat = "count") + theme(axis.title = element_blank())
})
}
The tricky part for me was with UI.
Instead of
sliderInput("percentInput1", "Percent of CoE", min = 0,
max = 100, value = c(0, 0))
I put
sliderInput("percentInput1", "Percent of CoE", min = 0,
max = 100, value = c(1, 99))
This resolved my problem. Works perfectly now.
And as I mentioned before, I use sliderInput with values, because I needed to select a range of data.
I am trying to make the colors in a ggvis plot remain consistent whenever the data is re-plotted based on the factors (unfortunately I apparently lack enough reputation to include pictures to show you).
I could only find one other post about this controlling-color-of-factor-group-in-ggvis-r but none of his solutions or workarounds work in my situation.
my data looks like this:
month year date entity_name prefix module module_entry_key entity_table_name count
0 January 2011 2011.000 AbLibrary LIB Base BS AB_LIBRARY 0
1 February 2011 2011.083 AbLibrary LIB Base BS AB_LIBRARY 0
2 March 2011 2011.167 AbLibrary LIB Base BS AB_LIBRARY 0
3 April 2011 2011.250 AbLibrary LIB Base BS AB_LIBRARY 0
4 May 2011 2011.333 AbLibrary LIB Base BS AB_LIBRARY 0
5 June 2011 2011.417 AbLibrary LIB Base BS AB_LIBRARY 0
3000 January 2011 2011.000 Vector VEC Base BS VECTOR 0
3001 February 2011 2011.083 Vector VEC Base BS VECTOR 0
3002 March 2011 2011.167 Vector VEC Base BS VECTOR 0
3003 April 2011 2011.250 Vector VEC Base BS VECTOR 569
3004 May 2011 2011.333 Vector VEC Base BS VECTOR 664
3005 June 2011 2011.417 Vector VEC Base BS VECTOR 775
I'm using a shiny app to display the page in a browser, and the relevant code is:
# render the plot, filtering for entities within the module minus any entities selected from the exclude panel
plot <- reactive({
if (input$filter==1){
data <- dplyr::filter(.data=melted, module_entry_key %in% input$module)
}
else{
data <- dplyr::filter(.data=melted, entity_name == input$entity)
}
data <- dplyr::filter(.data=data, !entity_name %in% input$excluded)
data$entity_name <- factor(data$entity_name)
data %>%
ggvis(x = ~date, y = ~count, fill = ~entity_name, key := ~id, fillOpacity := 0.5, fillOpacity.hover := 0.9) %>%
add_legend("fill", title="Entities") %>%
layer_points() %>%
add_tooltip(tooltipText, "hover") %>%
add_axis("y", title = "Count", title_offset = 50) %>%
add_axis("x", title="Date", title_offset=50, subdivide=6, tick_size_minor=3, format=parseDate(~year, ~month))
})
the filter is creating the subset of "melted" as "data" based on the filters in the UI (see picture)
since as far as I can tell there is no way to associate a fill color to a factor (the entity name) explicitly and the color is chosen by alphabetical order of the factors, whenever I make a new subset of data the colors are changed.
Is there any way to work around this?
(full shiny code)
server.R
library(ggvis)
library(shiny)
library(dplyr)
shinyServer(function(input, output, session){
modules_list <- as.character(c("Base" = "BS",
"Screening" = "SC",
"Protein Engineering" = "EN",
"Protein Production" = "PP",
"CD",
"PT",
"PD"))
#melted <- read.table(file="~/dataOut.txt", sep="\t", strip.white=TRUE, row.names=1, header=TRUE);
modules <- as.character(as.vector(unique(melted$module_entry_key)))
modules <- modules[modules != "null"]
entities <- as.character(as.vector(unique(melted$entity_name)))
entities <- entities[entities != "null"]
for (i in entities){
melted <- rbind(melted, data.frame(month=NA, year=NA, date=NA, entity_name=i, prefix=NA, module=NA, module_entry_key=NA, entity_table_name=NA, count=NA))
}
melted$id <- 1:nrow(melted)
#create ui checkbox for modules in the data
output$module_list <- renderUI({
checkboxGroupInput(inputId = "module",
label = "Module",
choices = modules,
selected = "BS")
})
#create the ui list for entities
output$entity_list <- renderUI({
checkboxGroupInput(
inputId = "entity",
label = "Entity",
choices = entities,
selected = "Vector"
)
})
#ex <- entities
#create the checkboxGroupInput with entities to 'exclude'
output$exclusion_entities <- renderUI({
checkboxGroupInput(inputId = "excluded", label = "Exclude",
choices = entities)
})
#update the excluded entities list with entities within a particular module
observe({
if (input$filter==1)
ex1 <- as.character(as.vector(unique(dplyr::filter(.data=melted, module_entry_key %in% input$module)$entity_name)))
updateCheckboxGroupInput(session, inputId = "excluded", "Exclude", choices=ex1, selected = input$excluded )
})
# render the plot, filtering for entities within the module minus any entities selected from the exclude panel
plot <- reactive({
if (input$filter==1){
data <- dplyr::filter(.data=melted, module_entry_key %in% input$module)
}
else{
data <- dplyr::filter(.data=melted, entity_name == input$entity)
}
data <- dplyr::filter(.data=data, !entity_name %in% input$excluded)
data$entity_name <- factor(data$entity_name)
data %>%
ggvis(x = ~date, y = ~count, fill = ~entity_name, key := ~id, fillOpacity := 0.5, fillOpacity.hover := 0.9) %>%
add_legend("fill", title="Entities") %>%
layer_points() %>%
add_tooltip(tooltipText, "hover") %>%
add_axis("y", title = "Count", title_offset = 50) %>%
add_axis("x", title="Date", title_offset=50, subdivide=6, tick_size_minor=3, format=parseDate(~year, ~month))
})
#function to add color and mouse-over effect to layer_points() (unused in this code)
points <- reactive({
layer_points(fillOpacity := 0.5, fillOpacity.hover := 1, fill.hover := "red")
})
#d3 date format for formatting x-axis text
parseDate <- function(year, month){
paste("d3.time.format(\"%Y\").parse(", year, ")", sep="")
}
#function for what to display in mouse-hover tooltip
tooltipText <- function(x) {
if(is.null(x)) return(NULL)
row <- melted[melted$id == x$id, ]
paste(row$entity_name, ": ", row$count, sep="")
}
#bind the plot to the UI
plot %>% #layer_points(fill = ~factor(entity_name)) %>%
bind_shiny("ggvis")
#select all button for modules
observe({
if (input$selectall ==0){
return(NULL)
}
else if ((input$selectall%%2)==0){
updateCheckboxGroupInput(session, inputId = "module", "Module", choices = modules)
}
else{
updateCheckboxGroupInput(session, inputId = "module", "Module", choices=modules, selected=modules)
}
})
#select all button for excluded entities
observe({
list <- as.character(as.vector(unique(dplyr::filter(.data=melted, module_entry_key %in% input$module)$entity_name)))
if (input$exclude_all ==0){
return(NULL)
}
else if ((input$exclude_all%%2)==0){
updateCheckboxGroupInput(session, inputId = "excluded", "Exclude", choices=list )
}
else{
updateCheckboxGroupInput(session, inputId = "excluded", "Exclude", choices=list, selected=list )
}
})
#---general output / debugging stuff ----#
output$table <- renderTable({dataInput()})
output$entity_selected = renderPrint({
list <- as.character(as.vector(unique(dplyr::filter(.data=melted, module_entry_key %in% input$module)$entity_name)))
entities[!entities %in% input$excluded & entities %in% list]
})
output$filter_value = renderPrint({input$filter})
output$modules = renderPrint({input$module})
output$link = renderPrint(input$selectall%%2)
#----------------------------------------#
})
ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("DB Analysis"),
sidebarLayout(
sidebarPanel(
width=3,
radioButtons(inputId="filter",
label="Filter",
choices = list("By Module" = 1, "By Entity" = 2),
selected = 1),
conditionalPanel(condition = "input.filter == 1",
uiOutput("module_list"),
actionButton("selectall", "Select All"),
uiOutput("exclusion_entities"),
actionButton("exclude_all", "Select All")
),
conditionalPanel(condition = "input.filter == 2",
uiOutput("entity_list")
)
),
mainPanel(
h2("Cumulative Entity Counts over Time (years)", align="center"),
#verbatimTextOutput("value"),
#verbatimTextOutput("filter_value"),
#verbatimTextOutput("modules"),
#tableOutput("table"),
ggvisOutput("ggvis"),
verbatimTextOutput("link"),
verbatimTextOutput("entity_selected")
#textOutput("entities_plot")
)
)
)
)
This is probably the best way to do it. Try something like this:
df[which(df$entity_name == "AbLibrary"),]$color <- "FF0000"
df[which(df$entity_name == "Vector"),]$color <- "#FFB90F"
For each one in your data frame. Set your fill then to color each time. The only problem is trying to make a legend. (I have been trying to figure that out, so if I find it I will edit this post.