Export plotly to powerpoint in R - r

Is it possible to export plotly/ggplotly plot to Powerpoint and keep its interactivity? I mean by that for example to allow user to change colors of plot lines, thickness, etc.
Example code:
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- ggplot(data = d, aes(x = carat, y = price)) +
geom_point(aes(text = paste("Clarity:", clarity))) +
geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~ cut)
gg <- ggplotly(p)
Btw, using webshot package to export plot as .png file is not a solution. And I should be able to code this solution and automate from R or any other programming language - online tools or any other applications where it should be clicked by user to get result do not solve the problem.

Related

How can I make a transition to a linear model?

From a database called "datoschile" that incorporates 6 variables, I have created a panel data called "magrupados3" that uses the variable "Periodo" as an identity variable and I have filtered thstrong texte information using only "Importaciones" and "Exportaciones" variables
This the excel file needed to work with this code
https://gitlab.com/pedritoandrade/how-can-i-make-a-transition-to-a-linear-model
datos <- read.xlsx("C:\\Users\\PEDRO ANDRADE 2019\\Desktop\\Curso Betametrica\\Analisis exploratorio y automatizacion de reportes\\datoschile.xlsx",
sheet = "Hoja1",
detectDates = T)`
magrupados3 <- melt(datos, id.vars = "Periodo")%>%
filter(variable == "Exportaciones" | variable == "Importaciones")`
Then with this data, I have created a graph using geom_line and geom_point and also the tendency line using geom_smooth. This is the code and the result you can see it here:
magrupados4 <- ggplot(data=magrupados3,aes(x=Periodo,y=value))+
geom_line()+geom_point()+facet_wrap(variable~.,scales = "free",ncol = 2)+
geom_smooth(method = "lm",formula= y~x,col="black",se=F)`
Graph
I want to make a transition of this graph. In other words, I want that geom_line and the regression line (geom_smooth) to appear simultaneously each year(my variable that represents year in my data is called "Periodo").
Can someone help me with this?
It seems that you need to use the R package gganimate in combination with the R packages: devtools, ggplot2, gifski, and av.
Check this link: https://gganimate.com/
Here is an example that I took from that website. It is working in my computer. You need the libraries that are in my example. Some libraries were not in the website example. Be careful with that. In your code, you did not use the last two lines of this example (transition_time(year) + ease_aes('linear')). Also, I guess that you did not install all the R libraries that are needed.
# install.packages('devtools')
# devtools::install_github('thomasp85/gganimate')
library(devtools)
library(gapminder)
library(ggplot2)
library(gganimate)
library(gifski)
library(av)
ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
facet_wrap(~continent) + labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy')+
transition_time(year) +
ease_aes('linear')

Convert ggplot to greyscale with stat_summary

I have an R package as a back-end engine for a GUI (JASP). I want to be able to have people convert their images to greyscale (for publication printing). For most plots, I can use scale_colour_grey(), but that doesn't work when colors are specified within stats_summary. For example:
# simulate data
set.seed(1212)
y = rnorm(100)
g = sample(c("a", "b"), 100, T)
d = data.frame(y=y, g=g)
### create ggplot
plot = ggplot(data=d, aes(x=g, y=y)) +
geom_jitter() +
stat_summary(fun="mean", geom="point", size=3, color="red") +
stat_summary(geom="errorbar", size=3, color="red") +
theme_bw()
### converting to greyscale doesn't work
plot + scale_colour_grey()
After some research, I learned you can dissect the ggplot object then rebuilt it:
### can rebuilt ggplot object, but not ideal
q <- ggplot_build(plot)
q$data[[2]]$colour <- "black"
q$data[[3]]$colour <- "black"
q <- ggplot_gtable(q)
plot = ggplotify::as.ggplot(q)
plot
That works fine, but I try to include as few dependencies in my R packages as possible. Do I really have to resort to another package (ggplotify) in order to modify the color coming from stat_summary?
A few notes: I don't want to have to modify the original stat_summary statement. Let's just pretend that cannot be modified. Also, let's assume I cannot add another package (aside from ggplot2, which is already loaded). Remember, I'm a "guest" in the JASP framework and I don't want to have to add another package to the list of packages they have to store.
You can actually get at the ggplot object before it is built, reach into the layer that has the coloured object and change it. Here's a full reprex:
library(ggplot2)
# simulate data
set.seed(1212)
y = rnorm(100)
g = sample(c("a", "b"), 100, T)
d = data.frame(y=y, g=g)
### create ggplot
p <- ggplot(data=d, aes(x=g, y=y)) +
geom_jitter() +
stat_summary(fun="mean", geom="point", size=3, color="red") +
stat_summary(geom="errorbar", size=3, color="red") +
theme_bw()
p
p$layers[[3]]$aes_params$colour <- "gray50"
p
If you want a more general approach to change a particular geom's colour, you could do something like this function:
recolour_geom <- function(gg_plot, geom, colour = "gray50")
{
ss <- which(sapply(p$layers, function(l) {
paste(gsub("GEOM|GG|PROTO", "", toupper(class(l$geom))),
collapse = "")}) %in% toupper(geom))
if (length(ss) > 0)
{
for (i in ss)
{
p$layers[[i]]$aes_params$colour <- colour
}
}
p
}
Which allows you to do, for example
recolour_geom(p, "errorbar", "blue")
recolour_geom(p, "point", "green")
Be aware though that this changes the ggplot by reference, so p is changed as a side effect of the function.
Created on 2020-08-14 by the reprex package (v0.3.0)

Create "The Economist" Style Plots in R?

This question has two parts, one more general and the other a specific case:
Is there a theme or template in R for producing plots that have similar appearance to the charts published in "The Economist" magazine? Examples in other contexts include: Create "The Economist" style graphs from python for python and set scheme economist for Stata.
Specifically, what would be the syntax (e.g., in ggplot2) to produce a groups bar plot that would look like the example below, colored shaped markers with bold lines spanning the range between them (left panel), or rectangular confidence intervals (right panel)?
Source: https://www.economist.com/graphic-detail/2020/04/01/covid-19-may-be-far-more-prevalent-than-previously-thought
Yes you have it in ggthemes (extension of ggplot2) with theme_economist and theme_economist_white.
For the bar plot, you will need to play with geom_bar and coord_flip (here)
Examples from ggthemes doc (here)
library("ggplot2")
library("ggthemes")
p <- ggplot(mtcars) +
geom_point(aes(x = wt, y = mpg, colour = factor(gear))) +
facet_wrap(~am) +
# Economist puts x-axis labels on the right-hand side
scale_y_continuous(position = "right")
## Standard
p + theme_economist() +
scale_colour_economist()
## White
p + theme_economist_white() +
scale_colour_economist()
How to reproduce the plot given in example
Since I cannot install SciencesPo package in my computer, I propose you a ggplot + ggthemes approach.
A good starting point might be the following approach. I use as an example the diamond dataset.
library(dplyr)
library(ggplot2)
library(ggthemes)
df <- diamonds %>%
group_by(cut) %>%
summarise(mean = mean(price), sigma = sd(price),
n = n())
df <- df %>%
mutate(int_minus = mean - 1.96*sigma/sqrt(n),
int_plus = mean + 1.96*sigma/sqrt(n))
And then the plot
ggplot(df) +
geom_segment(aes(x = int_minus, xend = int_plus, y = factor(cut), yend = factor(cut)), size = 2L, alpha = 0.4) +
geom_point(aes(x = mean, y = factor(cut)), shape = 15, color = "blue", size = 4L) +
theme_economist_white()

ggplot2/knitr: geom_col shows breaks in PDF but not in RStudio/HTML

When including a plot with geom_col in an R Markdown report knitted to pdf, the stacked breaks between observations are made visible as gray lines:
```{r}
library(ggplot2)
ggplot(data = midwest) +
geom_col(mapping = aes(x = state, y = poptotal))
```
But when I run the exact same code directly in R Studio (or knit to HTML), the columns are shown as solid:
Is there something special to do to make the different observations not be shown in a pdf (e.g., to make the pdf-knitted plot look like the HTML-knitted one)?
Did you Try using geom_bar() instead of geom_col(), because geom_col() was created afterwards, its basically geom_bar() only
```{r}
library(ggplot2)
ggplot(data = midwest) +
geom_bar(stat="identity",mapping = aes(x = state, y = poptotal))
```
It might work, try it and let me know
You can also set fill and check what happens
geom_bar(stat="identity",mapping = aes(x = state, y = poptotal,fill="gray60"))

How do I create a categorical scatterplot in R like boxplots?

Does anyone know how to create a scatterplot in R to create plots like these in PRISM's graphpad:
I tried using boxplots but they don't display the data the way I want it. These column scatterplots that graphpad can generate show the data better for me.
Any suggestions would be appreciated.
As #smillig mentioned, you can achieve this using ggplot2. The code below reproduces the plot that you are after pretty well - warning it is quite tricky. First load the ggplot2 package and generate some data:
library(ggplot2)
dd = data.frame(values=runif(21), type = c("Control", "Treated", "Treated + A"))
Next change the default theme:
theme_set(theme_bw())
Now we build the plot.
Construct a base object - nothing is plotted:
g = ggplot(dd, aes(type, values))
Add on the points: adjust the default jitter and change glyph according to type:
g = g + geom_jitter(aes(pch=type), position=position_jitter(width=0.1))
Add on the "box": calculate where the box ends. In this case, I've chosen the average value. If you don't want the box, just omit this step.
g = g + stat_summary(fun.y = function(i) mean(i),
geom="bar", fill="white", colour="black")
Add on some error bars: calculate the upper/lower bounds and adjust the bar width:
g = g + stat_summary(
fun.ymax=function(i) mean(i) + qt(0.975, length(i))*sd(i)/length(i),
fun.ymin=function(i) mean(i) - qt(0.975, length(i)) *sd(i)/length(i),
geom="errorbar", width=0.2)
Display the plot
g
In my R code above I used stat_summary to calculate the values needed on the fly. You could also create separate data frames and use geom_errorbar and geom_bar.
To use base R, have a look at my answer to this question.
If you don't mind using the ggplot2 package, there's an easy way to make similar graphics with geom_boxplot and geom_jitter. Using the mtcars example data:
library(ggplot2)
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot() + geom_jitter() + theme_bw()
which produces the following graphic:
The documentation can be seen here: http://had.co.nz/ggplot2/geom_boxplot.html
I recently faced the same problem and found my own solution, using ggplot2.
As an example, I created a subset of the chickwts dataset.
library(ggplot2)
library(dplyr)
data(chickwts)
Dataset <- chickwts %>%
filter(feed == "sunflower" | feed == "soybean")
Since in geom_dotplot() is not possible to change the dots to symbols, I used the geom_jitter() as follow:
Dataset %>%
ggplot(aes(feed, weight, fill = feed)) +
geom_jitter(aes(shape = feed, col = feed), size = 2.5, width = 0.1)+
stat_summary(fun = mean, geom = "crossbar", width = 0.7,
col = c("#9E0142","#3288BD")) +
scale_fill_manual(values = c("#9E0142","#3288BD")) +
scale_colour_manual(values = c("#9E0142","#3288BD")) +
theme_bw()
This is the final plot:
For more details, you can have a look at this post:
http://withheadintheclouds1.blogspot.com/2021/04/building-dot-plot-in-r-similar-to-those.html?m=1

Resources