I am having trouble getting matplotlib plots to show when deploying my app to shinyapps.io. The plots show as expected when deployed locally. Here is the entirety of my simple app. Any help/suggestions would be greatly appreciated as I have bashed my head against this wall for well over a week
library(shiny)
library(tidytuesdayR)
library(bslib)
library(shinythemes)
library(ggplot2)
library(tidyverse)
library(geomtextpath)
library(lubridate)
library(magrittr)
library(GGally)
library(DT)
library(ggtext)
options(reticulate.use_conda = FALSE)
library(reticulate)
# Create virtual env and install dependencies
reticulate::virtualenv_create("python35_env", python = "python3")
reticulate::virtualenv_install("python35_env", packages = c("pandas", "numpy", "matplotlib", "seaborn"))
reticulate::use_virtualenv("python35_env", required = TRUE)
# tuesdata <- tidytuesdayR::tt_load(2023, week = 50)
holiday_movies <- read_csv("holidaymovies.csv")
holiday_movies %<>% arrange(year, desc = TRUE)
choices <- c("R", "Python")
year_code <- holiday_movies$year
ui <- fluidPage(
titlePanel("Holiday Movies (TEST_print)"),
tabsetPanel(
tabPanel("Data Graphs",
column(6,
selectInput("choices", "Programming Language", choices = choices)
),
plotOutput("years_histo"),
br(),
br(),
br(),
br(),
br(),
br(),
column(6,
selectInput("year_1", "Select Year 1", choices = year_code)
),
column(6,
selectInput("year_2", "Select Year 2", choices = year_code)
),
plotOutput("years_chosen"),
br(),
br(),
br(),
br(),
br(),
br(),
br(),
br(),
br(),
br(),
align = "center",
"Another silly Shiny by: ",
span(strong("lorisipsum"), style = "color:blue"),
br(),
img(src = "photo.png", height = 75, width = 100),
br()
),
tabPanel("Dataset",
fluidRow(
column(width = 12, DTOutput('tbl'))
),
br(),
br(),
br(),
br(),
align = "center",
"Another silly Shiny by: ",
span(strong("lorisipsum"), style = "color:blue"),
br(),
img(src = "photo.png", height = 75, width = 100),
br()
)
)
)
server <- function(input, output, session) {
output$tbl = renderDT(
holiday_movies, options = list(lengthChange = TRUE, lengthMenu = c(10, 25, 50), scrollx = TRUE,
autoWidth = TRUE,
columnDefs = list(list(width = '200px', targets = c(1, 3))), rownames = FALSE))
output$years_histo <- renderPlot({
if (input$choices == "R"){
holiday_movies %>% group_by(year) %>% mutate(avg = median(average_rating)) %>% slice(1) %>% ungroup() %>% ggplot(aes(x = year, y = avg)) + geom_bar(stat = "identity", fill = "#235E6F") +
theme_bw() + theme(axis.text = element_text(size = 13), axis.title = element_text(size = 14)) + xlab("Median of the Average Ratings") + ylab("") +
labs(subtitle = " Plot made with <span style = 'color: #0000ff;'>**R** </span>",
caption = "Median of Movie Ratings by Year") +
theme(plot.caption = element_markdown(hjust = 0, lineheight = 1.5, size = 18),
plot.subtitle = element_markdown(size = 20))
}
else if(input$choices == "Python"){
plt <- reticulate::import("matplotlib.pyplot")
np <- reticulate::import("numpy")
pd <- reticulate::import("pandas")
sns <- reticulate::import("seaborn")
reticulate::py_run_string("import pandas as pd")
pd_df <- holiday_movies
pd$df <- pd_df
reticulate::py_run_string("grouped_df_internal = pd.df.groupby('year')['average_rating'].median()")
reticulate::py_run_string("grouped_df_internal = grouped_df_internal.to_frame(name = 'Median_Average_Rating')")
reticulate::py_run_string("grouped_df_internal = grouped_df_internal.reset_index(drop=False)")
pd$grouped_df <- reticulate::py_run_string("print(grouped_df_internal)")
pd$grouped_df <- pd$grouped_df$grouped_df_internal
fig <- plt$subplots()
Year = pd$grouped_df$year
avg_rating = pd$grouped_df$Median_Average_Rating
bar_labels = pd$grouped_df$Year
bar_colors <- c('tab:blue')
plt$bar(Year,avg_rating, color = bar_colors)
plt$title("Plot made with Python", horizontalalignment='center', fontsize=19)
plt$xlabel("Median of Movie Ratings by Year")
plt$figtext(0.35, 0.009, 'Median of Average Ratings', wrap=FALSE, horizontalalignment='right', fontsize=16)
test_1 <- plt$show()
}
})
output$years_chosen <- renderPlot({
year_df_1 <- holiday_movies %>% filter(year == input$year_1)
year_df_2 <- holiday_movies %>% filter(year == input$year_2)
year_df_3 <- rbind(year_df_1, year_df_2)
if (input$choices == "R"){
ggplot() + geom_histogram(data = year_df_1, aes(x = average_rating, y = ..count..), fill = "darkred", color = "white") +
geom_histogram(data = year_df_2, aes(x = average_rating, y = -..count..), fill = "darkgreen", color = "white") +
theme_bw() + theme(axis.text = element_text(size = 13), axis.title = element_text(size = 14)) + xlab("Average Rating") + ylab("") +
labs(subtitle = " Plot made with <span style = 'color: #0000ff;'>**R** </span>",
caption = "Year 1 in <span style = 'color: #8B0000;'>**red**</span>,Year 2 in <span style = 'color: #023020;'>**green** </span>") +
theme(plot.caption = element_markdown(hjust = 0, lineheight = 1.5, size = 18),
plot.subtitle = element_markdown(size = 20)) + xlim(c((min(year_df_3$average_rating)-1), (max(year_df_3$average_rating)+1)))
}
else if(input$choices == "Python"){
mpl <- reticulate::import("matplotlib.pyplot")
np <- reticulate::import("numpy")
pd <- reticulate::import("pandas")
sns <- reticulate::import("seaborn")
reticulate::py_run_string("import numpy as np")
reticulate::py_run_string("import seaborn as sns")
reticulate::py_run_string("import matplotlib.pyplot as plt")
pd_df1 <- year_df_1
pd$df1 <- pd_df1
pd_df2 <- year_df_2
pd$df2 <- pd_df2
reticulate::py_run_string("plt.clf()")
reticulate::py_run_string("plt.figure(figsize=(12, 8))")
reticulate::py_run_string("sns.histplot(x= pd.df1['average_rating'], stat='count', bins=30, edgecolor='black', color='darkred')") #THIS IS LINE 162
reticulate::py_run_string("heights, bins = np.histogram(pd.df2['average_rating'], bins=30)")
reticulate::py_run_string("heights *= -1")
reticulate::py_run_string("bin_width = np.diff(bins)[0]")
reticulate::py_run_string("bin_pos = (bins[:-1]) ")
reticulate::py_run_string("plt.bar(bin_pos, heights, width=bin_width, edgecolor='black', color='darkgreen')")
reticulate::py_run_string("plt.title('Plot made with Python; Year 1 in red, Year 2 in green', fontsize=18)")
reticulate::py_run_string("plt.xticks(fontsize=11)")
reticulate::py_run_string("plt.yticks(fontsize=11)")
reticulate::py_run_string("plt.xlabel('Average Rating', fontsize=14)")
reticulate::py_run_string("plt.ylabel('',fontsize=14)")
return(reticulate::py_run_string("plt.show()"))
}
})
}
shinyApp(ui = ui, server = server)