I would like to add interactivity to plots I've created in ggplot2. For 3 out of 4 horizontal bar plots I've created, this works fine when I wrap a plotting function in ggplotly()
. However, for the last one, the plot reneders incorrectly and plots a strange scale. I've searched through bug issues and found this one which may be related, but I'm running even more recent versions of the packages:
- plotly 4.9.1
- ggplot2 3.2.1
- R 3.6.1
# Data
sitename <- c('Heckscher Plgd',
'Strawberry Fields',
'Bethesda Terrace',
'Central Park West (Zone 1)',
'Reservoir (Northeast)',
'Central Park West (Zone 2)',
'Reservoir (Southeast)',
'Central Park South',
'Reservoir (Northwest)',
'Great Lawn And Cleopatra\'s Needle',
'Pilgrim Hill & Conservatory Water',
'Wollman Rink',
'Wien Walk And Arsenal',
'North Of The Arsenal',
'Wallach Walk And East Green',
'The Pool',
'Central Park West (Zone 3)',
'Central Park West (Zone 4)',
'Cedar Hill',
'79th St Yard And Summit Rock',
'Ross Pinetum')
Unique_Squirrel_ID <- c(100,89,60,32,36,57,85,61,123,43,64,89,44,22,55,46,38,85,64,50,9)
a <- data.frame(sitename,Unique_Squirrel_ID)
# Plot function
options(repr.plot.width=10)
#' Plots a bar chart of squirrel count by park region
#'
#' @param highlight (optional) a character vector of sitenames to highlight
#'
#' @return ggplot chart
#'
#' @examples
#' plot_counts_bar(c('Ross Pinetum', 'The Ramble'))
plot_counts_bar <- function(highlight = vector()) {
counts_full <- ggplot(a) +
geom_bar(aes(x = reorder(sitename, Unique_Squirrel_ID),
y = Unique_Squirrel_ID,
fill = Unique_Squirrel_ID),
stat = 'identity') +
coord_flip() +
scale_fill_gradient(low = 'white',
high = 'darkgreen',
limits = c(0,125),
name = 'Count') +
labs(title = 'Squirrel Distribution by Park Region', y = 'Squirrel Count', x = '') +
theme_minimal() +
theme(panel.grid.major.y = element_blank(), legend.position = c(0.8, 0.2), plot.title = element_text(hjust = 0.5))
if (length(highlight) == 0) {
counts_full
} else {
counts_full +
gghighlight(sitename %in% highlight,
label_key = Unique_Squirrel_ID)
}
}
plot_counts_bar()
When I run this code as-is (i.e. plot_counts_bar()
), I get the correct output:
But then when I run ggplotly(plots_counts_bar())
, I get the following:
Other, similarly coded bar charts are translated to ggplotly fine, and I have tried removing the scale_fill_continuous, coord_flip, and highlight clauses but those don't seem to be the issue. Any help is appreciated!