How I can zoom-in for a sankey plot in R-shiny? - shiny

I have been trying to create a R shiny dashboard including a sankey network. It is working without any problem, however some of the plots seem quite clutter due to high number of nodes and connections based on some input parameters. As an alternative solution, i am trying to implement zooming feature triggered by double click by the user, but I am getting an error of "unused element" by shiny.
The part of the ui code including double click is:
sankeyNetworkOutput("diagram",dblclick = "plot1_dblclick",
brush = brushOpts(id = "plot1_brush",resetOnNew = TRUE)
The server side code is:
output$diagram<- renderSankeyNetwork({
sankeyNetwork(Links = rv1()$links, Nodes = rv1()$nodes,
Source = "IDsource", Target = "IDtarget",
Value = "value", NodeID = "name",
iterations = 0, sinksRight=TRUE,
fontSize=13, nodePadding=20)
observeEvent(input$plot1_dblclick, {
brush <- input$plot1_brush
if (!is.null(brush)) {
ranges$x <- c(brush$xmin, brush$xmax)
ranges$y <- c(brush$ymin, brush$ymax)
} else {
ranges$x <- NULL
ranges$y <- NULL
}
})
})
I would really appreciate if I can get any help regarding to that!
Thanks!

Related

How to preview mermaid graph in RStudio viewer?

Background:
It's possible to "use of an external text file with the .mmd file extension can provide the advantage of syntax coloring and previewing in the RStudio Viewer" (DiagrammeR Docs)
What should look like this:
Problem:
In my minimal working example the graph is not rendered in the viewer panel but the plain text from the mermaid.mmd-file is printed (see below). How to fix this behavior, so that the chart is rendered?
mermaid.mmd:
graph LR
A-->B
Output in viewer panel:
The text inside the mermaid.mmd-file is printed in the viewer panel, but not the rendered graph
My Setup
RStudio 2022.07.2 (<- newest version)
R version 4.2.1 (2022-06-23 ucrt)
DiagrammerR version 1.0.9 (<- newest version)
knitr version 1.40 (<- newest version)
Technical Reason for the Problem
I found the problem. It's the implementation of the handling of extern .mmd-files in the DigrammeR::mermaid()-function.
Within the mermaid()-function the htmlwidgets::createWidget(name = "DiagrammeR", x = x, width = NULL, height = NULL, package = "DiagrammeR")-functions takes the processed input x and renders the graph. This functions expects an input in the format "\ngraph LR\nA-->B\n", where every input start and ends with "\n" and each line in your mermaid-code is also separated by "\n". But the input from an extern .mmd-file (readLines("mermaid.mmd", encoding = "UTF-8", warn = FALSE)) looks like this:
"graph LR" "A-->B" (separated strings for each line of mermaid-code)
Transforming the input into the required format can be done by mermaid.code <- paste0("\n",paste0(mermaid.code, collapse = "\n"),"\n")
Unfortunately this processing step is not implemented for extern .mmd-files in DigrammeR::mermaid()
Soultion
Build a new mermaid()-function, including the required processing step
Replace the mermaid()-function within the DiagrammeR-packages by the new function
# Build new mermaid()-function
mermaid.new = function (diagram = "", ..., width = NULL, height = NULL) {
is_connection_or_file <- inherits(diagram[1], "connection") ||
file.exists(diagram[1])
if (is_connection_or_file) {
diagram <- readLines(diagram, encoding = "UTF-8", warn = FALSE)
diagram <- paste0("\n",paste0(d, collapse = "\n"),"\n") # NEW LINE
}
else {
if (length(diagram) > 1) {
nosep <- grep("[;\n]", diagram)
if (length(nosep) < length(diagram)) {
diagram[-nosep] <- sapply(diagram[-nosep], function(c) {
paste0(c, ";")
})
}
diagram = paste0(diagram, collapse = "")
}
}
x <- list(diagram = diagram)
htmlwidgets::createWidget(name = "DiagrammeR", x = x, width = width,
height = height, package = "DiagrammeR")
}
#Replace mermaid()-function in DiagrammeR-package
if(!require("R.utils")) install.packages("R.utils")
library(R.utils)
reassignInPackage(name="mermaid", pkgName="DiagrammeR", mermaid.new, keepOld=FALSE)
# Test new function
DiagrammeR::mermaid("mer.mmd")
You can preview your codes as simple as running them like this:
library(DiagrammeR)
DiagrammeR(
"
**graph LR
A-->B**
")
You should be able to see
this

Aspose: Image overflow the table when using with shape in imageFieldMerging

When I try to insert image directly to the ImageFieldMergingArgs it appears properly in the table cell using the following code...
override fun imageFieldMerging(imageFieldMergingArgs: ImageFieldMergingArgs) {
val fieldValue = imageFieldMergingArgs.fieldValue
if (fieldValue is DataString) {
val decodedImage = fieldValue.decode()
imageFieldMergingArgs.imageStream = ByteArrayInputStream(decodedImage)
}
}
But when I'm trying to insert an image using Shape in MailMerge. then it is appearing outside the table. I'm using the following code
override fun imageFieldMerging(imageFieldMergingArgs: ImageFieldMergingArgs) {
val fieldValue = imageFieldMergingArgs.fieldValue
if (fieldValue is DataString) {
val shape = Shape(imageFieldMergingArgs.document, ShapeType.IMAGE)
shape.wrapType = WrapType.SQUARE
shape.aspectRatioLocked = false
shape.anchorLocked = true
shape.allowOverlap = false
shape.width = imageFieldMergingArgs.imageWidth.value
shape.height = imageFieldMergingArgs.imageHeight.value
imageFieldMergingArgs.shape = shape
}
}
is there any way I can add an image into the table cell using shape to imageFieldMergingArgs.
Thanks
When you specify imageFieldMergingArgs.imageStream the shape is inserted with WrapType.INLINE. In you second snippet you specify WrapType.SQUARE. This might be the difference. It is difficult to say exactly what is wrong without your template. But I would try specifying WrapType.INLINE. I tested both your code snippets on my side with a simple template an in both cases the image is inside table cell.

Accessing values inside eventReactive

I need help with a basic Shiny question. My goal is to make a simple math quiz app (What is 4 x 4?). I want to create values with one button, select a numeric answer, and then press another answer button. My problem is that i cannot find a way to access the values that are stored inside eventReactive. I have simplified the problem in the code below. The goal of this app is to ask for a number, and then to supply it. Thank you in advance!
# Goal: Fetch a number, then input that number, then receive paste("correct")/paste("incorrect)
ui <- fluidPage(
textOutput(outputId = "out"),
numericInput(inputId = "inn",
label = "",
value = 0),
actionButton("answer", "Answer"),
actionButton("question", "New Question"),
)
server <- function(input, output) {
data <- eventReactive(input$question,{
a <- sample.int(10,1)
paste("Enter",a)
})
output$out <- renderText({data()})
}
shinyApp(ui,server)
Here is what I would do
ui <- fluidPage(
textOutput(outputId = "out"),
numericInput(inputId = "inn", label = "", value = 0),
actionButton("answer", "Answer"),
actionButton("question", "New Question"),
)
server <- function(input, output, session) {
data <- reactiveValues(number = NULL)
output$out <- renderText({
if (is.null(data$number))
"Press 'New Question' button"
else
paste("Enter", data$number)
})
observeEvent(input$question, {
data$number = sample(10, 1)
})
observeEvent(input$answer, {
req(data$number, input$inn)
if (data$number == input$inn)
print("Correct")
# Do something exciting
else
print("Incorrect")
# Do something else
})
}
shinyApp(ui,server)
IMO it's good practice to keep reactive data and input/output generation separate. What I mean by that is that in the above example we use
reactiveValues to keep track of the changing data, and
observeEvent to monitor button clicks which may change specific elements of our reactive data,
renderText can print either fixed text or reactive data.

AVAssetExportSession make black video sometimes

I'm new baby for Video Processing use Swift 3. I try to merge multiple videos with AVAssetExportSession, and using AVVideoCompositionCoreAnimationTool to add overlay for final video.
The problem is sometimes the final video is perfect, but sometimes it just give me a black video with sound only even I didn't change anything :(
Anybody who ran into that problem same me please give an idea, thanks!
let mixComposition: AVMutableComposition = AVMutableComposition()
//Add assets here
let mainComposition: AVMutableVideoComposition = AVMutableVideoComposition(propertiesOf: mixComposition)
mainComposition.frameDuration = CMTimeMake(1, 30)
mainComposition.renderSize = renderSize
mainComposition.renderScale = 1.0
mainComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)
mainComposition.instructions = instructions
let exportSession: AVAssetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)!
exportSession.videoComposition = mainComposition
exportSession.audioMix = audioMix
exportSession.outputURL = outputURL
exportSession.outputFileType = AVFileTypeMPEG4
exportSession.shouldOptimizeForNetworkUse = true
exportSession.exportAsynchronously {
// Ended here
}

Windows Phone 7 Consuming Webservice WSDL

Ok I have written some basic generic webservices before but I have never tried to consume a 3rd party one.
The one I am trying to consume is
http://opendap.co-ops.nos.noaa.gov/axis/webservices/predictions/wsdl/Predictions.wsdl
I am not getting any results back from this what so ever and cannot figure out why.
More odd is it is not even reaching PredictionsClient_getPredictionsAndMetadataCompleted when I put a break point in the code it doesn't even reach it.
Any suggestions would be greatly appreciated
public void Bouy(double meters)
{
PredictionService.Parameters PredictionParams = new PredictionService.Parameters();
PredictionService.PredictionsPortTypeClient PredictionsClient = new PredictionService.PredictionsPortTypeClient();
GeoCoordinateWatcher gc = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
//gc.Position.Location.Latitude, gc.Position.Location.Longitude
GeoCoordinate myLocation = new GeoCoordinate(27.931631,-82.802582);
foreach (var bl in BouyLocation.GetAll())
{
GeoCoordinate otherLocation = new GeoCoordinate(bl.Lat, bl.Lon);
PredictionParams.beginDate = DateTime.Now.ToString("yyyyMMdd");
PredictionParams.endDate = DateTime.Now.AddDays(1.0).ToString("yyyyMMdd");
PredictionParams.stationId = bl.LocationID;
PredictionParams.timeZone = 0;
PredictionParams.unit = 1;
PredictionParams.dataInterval = 6;
PredictionsClient.getPredictionsAndMetadataCompleted += new EventHandler<PredictionService.getPredictionsAndMetadataCompletedEventArgs>(PredictionsClient_getPredictionsAndMetadataCompleted);
PredictionsClient.getPredictionsAndMetadataAsync(PredictionParams);
double mymeters = myLocation.GetDistanceTo(otherLocation);
if (mymeters < meters)
{
TextBlock DynTextBlock = new TextBlock
{
Name = "Appearance" + bl.LocationID,
Text = bl.LocationName + PredictionResult,
TextWrapping = System.Windows.TextWrapping.Wrap,
Margin = new Thickness(12, -6, 12, 0),
Style = (Style)Resources["PhoneTextSubtleStyle"]
};
DynamicAppearance.Children.Add(DynTextBlock);
this.nearByLocations.Add(new BouyLocationModel() { LocationName = bl.LocationName, LocationID = bl.LocationID, Lat = bl.Lat, Lon = bl.Lon });
}
}
var test = nearByLocations;
}
void PredictionsClient_getPredictionsAndMetadataCompleted(object sender, PredictionService.getPredictionsAndMetadataCompletedEventArgs e)
{
string err = e.Error.ToString();
PredictionResult = e.Result.ToString();
}
Loooking at the code you have here I think that you have used the importing of a ServiceReference to auto build the classes for you?
Unfortunately I have found that this is rather temperamental on WP7 and the only way I actually got it to work was when I connected it to a Microsoft WCF service. Connecting to anything else just doesn't work.
If you do google searches there are various pages talking about the fact it doesn't work and ways around it (which I couldn't get to work).
However, there are ways around it but it isn't as simple as the auto-generated stuff. Basically you do things manually.
Although there are other ways to manually create the web service what I did was follow the information in the following which worked well: http://zetitle.wordpress.com/2010/10/14/using-reactive-extensions-with-webrequest/
You will need to parse the response yourself but XML to LINQ works really well for this.
Hope that helps, or maybe someone will have the solution as it is something I am interested in knowing how to get working too