I tried to convert the ggplot geom-tile chart to plotly by using ggplotly function. However, I realized that the outcomes are different. Please refer for the link below to view the difference. Besides that, ggplotly chart also missing colorbar. Please help.
Image: Difference between ggplot and ggplotly chart
This is the code that I referred to : https://www.r-graph-gallery.com/285-waffer-map.html
Code:
madeUp=read.table("https://raw.githubusercontent.com/holtzy/R-graph-gallery/master/DATA/madeUp.csv", sep=",", header=T)
library(tidyverse)
theData <- madeUp %>%
group_by(X.Axis, Y.Axis, Group) %>%
dplyr::summarize(statistic=mean(randVals, na.rm = TRUE))
fig <- ggplot(theData, aes(X.Axis, Y.Axis)) +
coord_cartesian(xlim = c(0,20), ylim = c(0,20)) +
scale_x_continuous(breaks = seq(0,20)) +
scale_y_continuous(breaks = seq(0,20))+
geom_tile(aes(fill=statistic))+
guides(fill=guide_legend(title='Legend'))+
theme(
panel.background = element_rect(fill= 'white', color = 'white'),
panel.grid.major = element_line(color='#E0E0E0'),
panel.grid.minor = element_line(color='#E0E0E0')
)+
ggtitle('Wafer Map')+
facet_wrap(~Group)+
scale_fill_gradientn(colors = rainbow(100))
#Convert to ggplotly chart
fig <- ggplotly(fig)
Thanks
Looks like you stumbled over a bug (or two) in ggplotly
(maybe you should raise an issue on github).
The first issue is that the "gaps" in the dataset get lost when converting the ggplot via ggplotly
.
The second issue is that ggplotly
fails to convert the binned colorbar added by guides(fill=guide_legend(title='Legend'))
.
As a workaround for
X.Axis
, Y.Axis
and Group
.Not perfect but this way the conversion via ggplotly
gives you the correct plot and a legend. Try this:
madeUp=read.table("https://raw.githubusercontent.com/holtzy/R-graph-gallery/master/DATA/madeUp.csv", sep=",", header=T)
theData <- madeUp %>%
group_by(X.Axis, Y.Axis, Group) %>%
dplyr::summarize(statistic=mean(randVals, na.rm = TRUE)) %>%
ungroup()
# Expand the Dataset to includ all Combinations of X.Axis, Y.Axis and Group
theData1 <- tidyr::expand_grid(X.Axis = 0:49, Y.Axis = 0:30, Group = LETTERS[1:6]) %>%
dplyr::left_join(theData)
fig <- ggplot(theData1, aes(X.Axis, Y.Axis)) +
coord_cartesian(xlim = c(0,20), ylim = c(0,20)) +
scale_x_continuous(breaks = seq(0,20)) +
scale_y_continuous(breaks = seq(0,20))+
geom_tile(aes(fill=statistic))+
# Remove the binned colorbar
# guides(fill=guide_legend(title='Legend'))+
labs(fill = "Legend") +
theme(
panel.background = element_rect(fill= 'white', color = 'white'),
panel.grid.major = element_line(color='#E0E0E0'),
panel.grid.minor = element_line(color='#E0E0E0')
)+
ggtitle('Wafer Map')+
facet_wrap(~Group)+
# in case of ggplot2: Set the fill color for NA to "transparent"
scale_fill_gradientn(colors = rainbow(100), na.value = "transparent")
fig
ggplotly(fig)