Unable to suppress x-axis label in a plotly violin plot - r

I just installed the latest plotly R package (devtools::install_github("ropensci/plotly")).
I'm trying to generate a violin plot for a single variable and I would like to suppress the x-axis label.
I tried:
library(dplyr)
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")
plot_ly(y =~ df$total_bill,type = 'violin',
box = list(visible = T),
meanline = list(visible = T)) %>%
layout(xaxis = list(title = ""),yaxis = list(title = "Total Bill",zeroline = F))
But I'm getting "trace 0" as the x-axis label:
I tried playing around with the x0 parameter but couldn't get a violin with no x-axis label.
Any idea?

Here's an example using ggplot2 + ggplotly:
library(dplyr)
library(plotly)
librart(ggplot2)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")
# Generate a ggplot with a violin plot and a boxplot
vioplot <- ggplot(df, aes(x = "", y=total_bill)) +
geom_violin(fill = "blue", alpha = 0.3) +
geom_boxplot(fill = "blue", alpha = 0.3) +
xlab("") + ylab("Total bill")
# Render the ggplot as a plotly object using ggplotly()
ggplotly(vioplot)
Here is the resulting plotly
P.S. I wan't able to reproduce your plot using plot_ly(). I Got an error "Error: Trace type must be one of the following:...". Anyway I'm not a big fan of the plot_ly() way. I always go first through a ggplot.

Related

How to use plotly on bar chart in R Shiny App

I have a bar chart that I want to make interactive in my R Shiny app using plotly.
When it is rendered as a plot, everything is fine using ggplot:
#Bar plots
ggplot(data = df_continents) +
geom_bar(aes(x=country, y=coal_co2), stat="identity", fill="#2596be") +
scale_y_continuous(labels = number_format())`
But, when I try to use plotly, the format gets messed up in an incredible way:
#Bar chart - Adding Labels
ticklabels <- seq(from=0, to=round(max(df$coal_co2*100000)), by=100000)
ticktexts <- c(0,paste(ticklabels[-1]/1000, " 000", sep=""))
output$bar <- renderPlotly({
df %>%
plot_ly(x =~ country, y = ~ coal_co2, type = "bar", marker = list(color = "#2596be")) %>%
layout(yaxis=list(tickvals = ticklabels,
ticktext = ticktexts
))
})
So, I'm not sure what is the problem here, why do I have those white horizontal lines inside the bars?. How do I get my bar chart plot to look like the first screenshot?.

How to make plotly graph function less laggier and more distinct in R for many datapoints?

Currently, I have a lot of datapoints, and its not really distinguishable by color. How can I make the colors more distinguishiable, or do I have to make a graph other than scatterplot that may better display my data? Also, My plotly graph is super laggy and has 40 warning messages. How do I make a plotly graph that is less laggier and more distinguishable by color. My ggplot doesn't have this lagginess problem but I don't want to use ggplot because I want it to be interactive.
#ggplot function for graph
scatter_n <- function(new_data) {
b <- ggplot(data = new_data, aes(x = current_votes, y = percent, color = candidate)) +
geom_point()
return(b)
}
scatter_n(df3)
([![ggplot][1]][1]
# Plotly function for graph
scatter_b <- function(new_data) {
c <- plot_ly(data = new_data, x = ~current_votes, y = ~percent, color = ~candidate, Type = "scatter", Mode = "markers") %>%
layout(
title = "Percentage of Votes for each candidate by population",
xaxis = list(title = "Current Votes"),
yaxis = list(title = "Percentage", ticksuffix = "%")
)
return(c)
}
I'm not entirely sure about what you want to represent. Both your axes represent almost the same data (votes), so a scatter plot might not be the most appropriate way of visualizing it. What about using geom_col() to plot the candidates in the x axis and the number of votes in the y axis?
If you want to add the percentages, you can add it as text with geom_text() on top of the bars.
You can also turn the ggplot graph into plotly with ggplotly(), to keep it interactive

`showticklabels = FALSE` in `plotly::layout()` fails with multiple subplots

Take the following "Horizontal grid" example from the Plotly ggplot2 Library
I want to omit the labels from the X axes in both subplots, like:
The way to do this should be, allegedly, by using the layout() function and including configuration parameter xaxis = list(showticklabels = FALSE). See however the output in the following reprex:
library(tidyverse)
library(reshape2)
library(plotly)
p <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1) +
facet_grid(. ~ sex)
ggplotly(p) %>%
layout(xaxis = list(showticklabels = FALSE))
As you can see, only the first subplot is affected.
I have already tried by rendering each subplot as a plotly object, and then using the subplot function:
tips %>% group_split(sex) %>% map(
~{
p <- ggplot(., aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1)
ggplotly(p)
}
) %>%
subplot(shareY = TRUE) %>%
layout(xaxis = list(showticklabels = FALSE))
The result is the same.
Also, calling layout(., xaxis = list(showticklabels = FALSE)) for each subplot individually fails, as subplot() apparently overrides the layout of the subplots.
Additionally, inspection of the JSON object seems to show that only one layout attribute is generated for the whole subplot, which I understand should control the properties of all subplots.
Any idea on how to solve this? Any help would be much appreciated!
To achieve what you desire, removing all x-axis labels from the ticks, I would remove them using your ggplot theme. Thus before you call ggplotly
p <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) +
geom_point(shape=1) +
facet_grid(. ~ sex) +
theme( axis.text.x=element_blank()) # remove x-labels
p
ggplotly(p)

Shiny w/ ggplot produces erroneous legend: duplicate legend entries with facets

I want to plot a facet plot with added geom_hline and show the line in the legend. However, when I add the line to the legend, all entries duplicate to the number of facets.
How can I avoid this behaviour?
Here is my MWE
library(shiny)
library(plotly)
library(ggplot2)
df <- mpg
# Define UI for application that draws a histogram
ui <- fluidPage(
mainPanel(
plotlyOutput('graph')
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$graph <- renderPlotly({
p <- ggplot2::mpg %>%
plot_ly %>%
ggplot() +
geom_point(aes(displ, hwy, color = class))
facet <- p + facet_wrap(~year)
facet + geom_hline(aes(yintercept = 20, linetype = 'hline20'), color = '#00b700') +
scale_linetype_manual(name = 'line', values = 1,
guide = guide_legend(aes = list(color = "#00b700")))
})
}
# Run the application
shinyApp(ui = ui, server = server)
The problem is not shiny nor ggplot2. The problem is the conversion of a ggplot2 object into a plotly object.
Below I've isolated the ggplot steps from the plotly step and completely removed shiny from the picture.
p <- ggplot2::mpg %>%
ggplot() +
geom_point(aes(x = displ, y = hwy, color = class))
facet <- p + facet_wrap(~year)
final <- facet + geom_hline(aes(yintercept = 20, linetype = 'hline20'), color = '#00b700') +
scale_linetype_manual(name = 'line', values = 1, guide = guide_legend(aes = list(color = "#00b700")))
print(final)
The above displays fine.
ggplotly(final)
This above has the same display errors as yours, without involving shiny.
Legend issues and other display issues are common when converting ggplot2 objects to plotly objects. Plotly and ggplot2 are completely independent plotting frameworks with their own syntax and graphics objects. Plotly provides conversion function methods but things still get lost in translation from one format to the other, because there is not a complete equivalency between them.
I'd recommend trying to implement your plot in native plotly syntax instead of trying to convert it from ggplot2.

Using ggplotly with ggplot

I have a script using ggplotly to produce a couple of interactive charts. I then try to produce addition charts that are not interactive using ggplot. They refuse to plot even if I introduce Sys.sleep() pauses.
Is there a reason why one cannot mix the interactive Javescript ggplotly plots with non-interactive ggplot plots in the same script? I cannot find anything answers regarding this question.
Update: Here is a mini-version of the code I am using. Actually, it doesn't work in RStudio. The second plot appears to write on top of the first one. Whatever plot is created last appears to overwrite the previous plot. If I remove the call to 'ggplotly' and just print the ggplot construction, all is well. It has something to do with the call to ggplotly.Conversely, if I use ggplotly for both charts, all is well. Seems they don't mix.
library("ggplot2")
library("plotly")
test_data <- data.frame(A = c(1,5,7,4,2),
B = c(3,3,6,8,4),
C = c(6,2,9,4,5))
my_dates <- as.Date(c("2010-01-01", "2010-02-01",
"2010-03-01", "2010- 4-01",
"2010-05-01"))
xts_data <- xts(test_data, order.by = my_dates)
p <- autoplot(xts_data, facets = NULL) +
guides(color = guide_legend(override.aes = list(size = 2))) +
geom_line(size = 1)
print(ggplotly(p))
new_df <- data.frame(P = c(70, 70, 70),
Category = c("A", "B", "C"),
Value = c(5, 15, 10))
p <- ggplot(data = new_df, aes(
x = Category, y = Value)) +
geom_bar(position = position_dodge(), stat = "identity")
print(p)
The "problem" I was having is the ggplot chart is displayed in the Plot pane and the ggplotly charts are displayed in the Viewer pane. Problem solved.

Resources