When I want to export a wordcloud2 picture, the wordcloud seems to be recalculated and looks very different from the one in the viewer.
How can I prevent R from creating another picture?
library(wordcloud2)
wordcloud2(demoFreq[demoFreq$freq>7,],minRotation = 0, maxRotation = 0)
Pictures: https://drive.switch.ch/index.php/s/8WIkGEM88wd4UXc
Adding shuffle = FALSE keeps the words in place.
Defining nonrandom colors fixes the colors. Maybe with a color vector.
library(wordcloud2)
minfreq=10
upperpart= demoFreq[demoFreq$freq>minfreq,]
colorvector = rep(c('red','skyblue'), length.out=nrow(upperpart))
wordcloud2(demoFreq[demoFreq$freq>minfreq,],minRotation = 0,
maxRotation = 0,shuffle=FALSE, color=colorvector)
you should just add shuffle = FALSE in your function and in case you want to control the colors you can create a color palette using the rainbowfunction with the number of rows of your data input:
dataInput <- demoFreq[demoFreq$freq>7,]
my_colors <- rainbow(nrow(dataInput), start = 0.1) # check ?rainbow for more infos
wordcloud2(dataInput, minRotation = 0, maxRotation = 0, shuffle = F, color = my_colors)
gives you:
Hope this helps!
Related
I want to plot a animated 3D scatterplot and save it as gif. I followed the code provided by the R Graph Gallery example: https://www.r-graph-gallery.com/3-r-animated-cube.html.
library(rgl)
library(magick)
options(rgl.printRglwidget = TRUE)
# Let's use the iris dataset
# iris
# This is ugly
colors <- c("royalblue1", "darkcyan", "oldlace")
iris$color <- colors[ as.numeric( as.factor(iris$Species) ) ]
# Static chart
plot3d( iris[,1], iris[,2], iris[,3], col = iris$color, type = "s", radius = .2 )
# We can indicate the axis and the rotation velocity
play3d( spin3d( axis = c(0, 0, 1), rpm = 20,dev = cur3d()),startTime = 0, duration = 10 )
# Save like gif
movie3d(
movie="3dAnimatedScatterplot",
spin3d( axis = c(0, 0, 1), rpm = 20,dev = cur3d()),
startTime = 0,
duration = 10,
dir = ".",
type = "gif",
clean = T,
fps=10,
convert=T
)
plot3d was successed output a 3d scatter plot.
Static 3d scatter plot
But the final output: 3dAnimatedScatterplot.gif,just a black image
3dAnimatedScatterplot.gif
when I set clean=F, all frame images are black. So, I guess the play3d() was not working.
Can anyone provide any help to me ? Thanks a lot !
Most likely snapshot3d isn't working for you. Try it with the option webshot = FALSE instead of the default webshot = TRUE. That uses a different mechanism for saving the image.
I have been trying for some time to debug my Shiny gadget but still cannot manage it. Really appreciate any help.
My gadget consists of a scatterplot generated with Plotly. The user can click one of the points, which will allow you to change some parameters associated with that point. To emphasise the fact that the user has selected that point, I wanted to highlight the selected point.
Alternatively, the user can also select a point from a dropdown menu, which also should highlight the corresponding point.
As an added feature, I want to additionally highlight points that are below a certain threshold on the x axis. This threshold is represented by a dotted line, which you can turn on and off, and move the value of the threshold.
In summary, the points on the plot should all be blue circles, except for the following two cases:
if it is clicked, i.e. it is the "active point" (this should create a red border around the point)
if it is below the threshold on the x-axis (the point should turn to an orange square)
If it is active AND below the threshold, it should be an orange square with a red border, as you would expect.
My gadget works, kind of. But in some cases not. In the example below, one of the points is already below the threshold, but when I select that point, the red marker appears on another point! Despite the active variable being the correct one.
I also get a weird behaviour that the points turn purple if the threshold is below all of the points. But if I move the threshold to be above one of the points, the colours are corrected.
I have a suspicion that this is something to do with the points being on different traces? Therefore when I try to highlight certain points, perhaps I am not indexing the vector as I am expecting. But I am finding it really difficult to debug inside Shiny and Plotly, and I have no good understanding of the Plotly object, so I don't have much clue as to what is going on.
The code below is a reproducible example. You have to run "dat1" through the "rew8r" function. I have taken out other features of the app to try to focus on the problem. Thanks very much to anyone who might take the time to have a look at this, and give any hints!
library(plotly)
library(dplyr)
library(shiny)
library(reactable)
dat1 <- data.frame(
Indicator = c("v1","v2","v3"),
Weight = rep(1,3),
Correlation = c(0.1, 0.8, 0.6) )
rew8r <- function(dat){
# get indicator names
inames <- dat$Indicator
## Create the shiny UI layout
ui <- fluidPage(
# the side panel
sidebarPanel(
selectInput("vseldrop", "Select indicator here or by clicking a point on plot.",
c("<Select>",inames)),
hr(style = "border-top: 1px solid #000000;"),
fluidRow(
column(6,numericInput("locorval", "Low correlation threshold:", 0.2, min = -1, max = 1, step = 0.05)),
column(6,br(),checkboxInput("locorsw", "Enable", value = FALSE)))
),
# the main panel (graph, table, etc)
mainPanel(
plotlyOutput("corrplot"),
textOutput("info")
)
)
## Create the Shiny Server layout
server <- function(input, output, session) {
# this is the plotly click data
event.data <- reactive({event_data(event = "plotly_click", source = "scplot")})
# First, monitor which variable is active
# Create reactive value for active var
acvar <- reactiveVal(NULL)
# update active variable via plot click
observeEvent(event.data(),{
acvar(event.data()$key)})
# update active variable via dropdown
observeEvent(input$vseldrop,
acvar(input$vseldrop))
## Create the plotly plot that compares price vs scoops
output$corrplot <- renderPlotly({
# colours around markers when selected or not
lincol <- ifelse(inames %in% acvar(), "red", "blue")
# size of line around marker (set to 0 if not selected)
linsize <- ifelse(inames %in% acvar(), 3, 0)
# symbol when above/below corr threshold
symbs <- if(input$locorsw==TRUE){c(16,15)}else{c(16,16)}
# colour when above/below threshold
pcols <- if(input$locorsw==TRUE){c("blue", "orange")}else{c("blue", "blue")}
# generate main plot
p <- plot_ly(dat, x = ~Correlation, y = ~Weight, type = "scatter", mode = "markers",
text = ~Indicator, key = ~Indicator, source = "scplot",
marker = list(size = 10, line = list(color = lincol, width = linsize)),
symbol = ~Correlation < input$locorval, symbols = symbs,
color = ~Correlation < input$locorval, colors = pcols) %>%
layout(showlegend = FALSE, yaxis = list(
range = c(0, 1.25),
autotick = FALSE,
dtick = 0.25),
xaxis = list(
range = c(-0.5, 1),
autotick = FALSE,
dtick = 0.2))
# add low correlation line, if activated
if(input$locorsw==TRUE){
p <- p %>% add_segments(x = input$locorval, xend = input$locorval, y = 0, yend = 1.25,
marker = list(color = 'red', opacity=0),
line = list(dash = 'dash')) %>%
layout(showlegend = FALSE)
}
p
})
# Text info
output$info <- renderText({
paste(acvar(), class(acvar()))
})
# update dropdown menu
observeEvent(acvar(),{
updateSelectInput(session, "vseldrop", selected = acvar())
})
}
runGadget(ui, server, viewer = browserViewer())
}
I wanted to have my conditions labelled on the heatmap I am making for DGE.
This code:
mat <- assay(rld)[topVarGenes,]
condition = c("black", "orange")
names(condition) = c("Dark", "Light")
ann_colors = list(condition = condition)
pheatmap(mat, color = colorRampPalette(rev(brewer.pal(n = 7, name = "RdYlBu")))(24), annotation_colors = ann_colors[1], border_color = "grey60", fontsize = 12, scale = "row")
produces this heatmap:
But, this heatmap doesn't have the conditions labelled above the columns like I wanted. So I tried this code:
annotation <- data.frame(annotation)
pheatmap(mat, annotation = annotation, color = colorRampPalette(rev(brewer.pal(n = 7, name = "RdYlBu")))(24), border_color = "grey60", fontsize = 12, scale = "row")
Which almost works, but doesn't use the colors I want to label the conditions (samples 1-3 are "dark" condition and are to be labelled black and samples 4-6 are "light" condition and are to be labelled orange). This graph also includes a funky column label under condition for sample which is redundant and I don't know how to get rid of it. Also, the data.frame(annotation) is an excel sheet I imported of samples and corresponding conditions.
Adding back the annotation_colors to the code:
pheatmap(mat, annotation = annotation, color = colorRampPalette(rev(brewer.pal(n = 7, name = "RdYlBu")))(24), annotation_colors = ann_colors, border_color = "grey60", fontsize = 12, scale = "row")
produces this error:
Error in convert_annotations(annotation_col, annotation_colors) :
Factor levels on variable condition do not match with annotation_colors
Lastly, I tried this bit of code I found in a stack overflow post to define annotation, which gets R to use the correct colors, but they are not in the correct order for the conditions because the %% 2==0 causes it to label every other sample as 'light', but I can't think of anything else to do. Here is the code:
annotation <- data.frame(condition = factor(1:6 %% 2==0, labels = c("Dark", "Light")))
Help is greatly appreciated!
It's not so clear in the vignette, but you can follow the steps below to generate the right data.frame and list, no reason not to work:
First I make a matrix like yours:
library(pheatmap)
M = cbind(matrix(runif(30,min=0,max=0.5),ncol=3),
matrix(runif(30,min=0.3,max=0.8),ncol=3))
rownames(M) = paste0("row",1:10)
colnames(M) = paste0("sample",1:6)
Let's say first 3 columns are "light", and last 3 columns are "dark". We create a data.frame for this, important thing is to have rownames that match the colnames of your matrix:
ann_column = data.frame(
condition = rep(c("light","dark"),each=3))
rownames(ann_col) = colnames(M)
ann_column
condition
1 light
2 light
3 light
4 dark
5 dark
6 dark
Now for the colors, you need a list, and the names need to match the data frame above, and inside the light, you specify what factor matches what color, so:
ann_colors = list(condition = c(dark="black",light="orange"))
And we draw it:
pheatmap(M,annotation_col=ann_col,annotation_colors=ann_colors)
I'm facing an issue while trying to format/style an existing excel file with data.
I want to change the format of a numeric cell, add background color and a border.
require(XLConnect)
wb <- loadWorkbook("example.xlsx", create = FALSE)
cs <- createCellStyle(wb)
setDataFormat(cs, format = "###,##0")
setFillBackgroundColor(cs, color = XLC$"COLOR.YELLOW")
setBorder(cs, side = "all", type = XLC$"BORDER.THIN",
color = XLC$"COLOR.BLACK")
setCellStyle(wb, sheet = "PSNB", row = 24, col = 3, cellstyle = cs)
saveWorkbook(wb)
After running the above code, the cell doesn't have the background color (Yellow) and the data format persisted.
When i double click on the cell, i can see the background color changing to yellow and the commas(Ex: 100,000) appearing.
Any help would be greatly appreciated!
I'm using XLConnect 0.2-13
I think you are rather looking to set the fill foreground color instead of the fill background color. Background colors are usually only needed in conjunction with non-solid fill patterns (see setFillPattern).
The following may do what you are looking for:
require(XLConnect)
wb <- loadWorkbook("example.xlsx", create = FALSE)
cs <- createCellStyle(wb)
setDataFormat(cs, format = "###,##0")
setFillForegroundColor(cs, color = XLC$"COLOR.YELLOW")
setFillPattern(cs, fill = XLC$FILL.SOLID_FOREGROUND)
setBorder(cs, side = "all", type = XLC$"BORDER.THIN",
color = XLC$"COLOR.BLACK")
setCellStyle(wb, sheet = "PSNB", row = 24,col = 3, cellstyle = cs)
saveWorkbook(wb)
Note the use of setFillForegroundColor and setFillPattern instead of setFillBackgroundColor.
When using chartSeries, by default it also shows on the top left of the plot the last value. Is there any way to prevent it from doing it?
When adding a new TA with addTA, you can avoid the last value on the plot by setting the argument legend = "", but only if you're making a new plot for the TA. If the TA is on a previously plotted graphic, it'll show the last value regardless of what you put in the legend argument.
getSymbols ("AAPL", src = "google")
chartSeries(AAPL)
What can I use here to prevent it from printing the last value on the plot?
addTA(EMA(Cl(AAPL)), on = 1, legend = "")
This still prints the last value on the top left of the plot. The weird part is that it doesn't do it if you're plotting on a new plot like this:
addTA(EMA(Cl(AAPL)), legend = "")
Is it like this by default, or is there something I can do to get around it?
The last value is shown by default (yes, annoyingly). You'll likely have to modify the source code to remove the last number showing in addTA.
I don't use addTA, but rather add_TA and chart_Series, because I think they look much better (second generation charts for quantmod). Here is a solution that removes the last number from showing for the add_TA version. But you must be willing to modify the source code.
In add_TA, you'll need to modify approximately lines 56-60 of the source:
Replace the text.exp, which is this:
# this is inside add_TA:
if (is.na(on)) {
plot_object$add_frame(ylim = c(0, 1), asp = 0.15)
plot_object$next_frame()
text.exp <- expression(text(x = c(1, 1 + strwidth(name)),
y = 0.3, labels = c(name, round(last(xdata[xsubset]),
5)), col = c(1, col), adj = c(0, 0), cex = 0.9,
offset = 0, pos = 4))
plot_object$add(text.exp, env = c(lenv, plot_object$Env),
with these modifications:
if (is.na(on)) {
plot_object$add_frame(ylim = c(0, 1), asp = 0.15)
plot_object$next_frame()
text.exp <- expression(text(x = c(strwidth(name)), # <- affects label on the subchart
y = 0.3, labels = name, col = c(col), adj = c(0), cex = 0.9,
offset = 1, pos = 4))
plot_object$add(text.exp, env = c(lenv, plot_object$Env),
expr = TRUE)
...
and assign this modified code to a new variable, called say add_TA.mine:
add_TA.mine <- function (x, order = NULL, on = NA, legend = "auto", yaxis = list(NULL,
NULL), col = 1, taType = NULL, ...)
{
lenv <- new.env()
lenv$name <- deparse(substitute(x))
lenv$plot_ta <- function(x, ta, on, taType, col = col, ...) {
xdata <- x$Env$xdata
....
[all the code for the rest of the function with modifications]....
}
}
plot_object
}
Now, just run the code with the modified function
library(quantmod)
getSymbols("AAPL")
environment(add_TA.mine) <- environment(get("add_TA", envir = asNamespace("quantmod")))
assignInNamespace(x = "add_TA", value = add_TA.mine, ns = "quantmod")
chart_Series(AAPL, subset = "2017")
add_TA(RSI(Cl(AAPL)))
quantmod:::add_TA(RSI(Cl(AAPL)))
You can see the last value is no longer printed:
(You could make the same kinds of changes in the old addTA code (perhaps via chartSeries if you really want to stick to the old plots)
If you're happy with the changes, and want to make them permament in add_TA, you can recompile the quantmod source code yourself with your modifications (i.e. you need to download the quantmod source code and recompile the package) . If you make a mess of things you can always redownload the original quandmod source code again.