I'm doing right now a shiny web app, in order to plot some data that comes from csv files.
Here my code concerning the shiny app :
# install.packages("shiny")
library(shiny)
source("test.R")
# library(...) that I need
# User Interface
ui <- fluidPage(
titlePanel("Affichage de l'indice EPU"),
sidebarLayout(
sidebarPanel(
helpText("Choix des paramètres"),
selectInput("var",
label = "Choisir une variable à afficher",
choices = list("Global",
"France",
"Royaume-Uni"),
selected = "Percent White"),
dateRangeInput("dateRange",
label = "Intervalle de temps : ",
format = "mm/yyyy",
language="fr",
start = "2018-01-01",
end = Sys.Date(),
startview = "year",
separator = " - ")
),
mainPanel(plotOutput("p")
)
)
)
# Define server logic required to draw a histogram ----
server <- function(input, output) {
output$p <- renderPlot({
graph_epu()
})
}
shinyApp(ui = ui, server = server)
For the moment, I don't use input in User Interface function, I just want to plot the data.
My function, inside the file test.R, do some things in order to generate a graph.
Here my function :
graph_epu <- function(){
# On importe les données du csv dans les dataframes
df_lesechos <- read.csv(file = "data/df_lesechos.csv", sep=",")
df_latribune <- read.csv(file = "data/df_latribune.csv", sep=",")
# On supprime le jour pour le remplacer par 01
df_lesechos$Date <- substr(df_lesechos$Date,1,7)
df_latribune$Date <- substr(df_latribune$Date,1,7)
df_lesechos$Date <- paste(df_lesechos$Date,"-01",sep="")
df_latribune$Date <- paste(df_latribune$Date,"-01",sep="")
# Transforme la colonne Occurences au format numérique
#df_lesechos <- transform(df_lesechos, Occurences = as.numeric(Occurences))
#df_latribune <- transform(df_latribune, Occurences = as.numeric(Occurences))
df_lesechos$Occurences <- as.numeric(df_lesechos$Occurences)
df_latribune$Occurences <- as.numeric(df_latribune$Occurences)
# On convertit la colonne date au format Date
df_lesechos <- transform(df_lesechos, Date = as.Date(Date))
df_latribune <- transform(df_latribune, Date = as.Date(Date))
# On élimine les valeurs datant d'avant 2018
df_lesechos <- df_lesechos[!(df_lesechos$Date < "2018-01-01"),]
df_latribune <- df_latribune[!(df_latribune$Date < "2018-01-01"),]
# On groupe par mois et on fait la somme des occurences
df_lesechos <- df_lesechos %>% group_by(Date) %>% summarise(Occurences = sum(Occurences)) %>% arrange(desc(Date))
df_latribune <- df_latribune %>% group_by(Date) %>% summarise(Occurences = sum(Occurences)) %>% arrange(desc(Date))
# Calcul de la variance pour chaque journal
echos_var <- var(df_lesechos$Occurences)
tribune_var <- var(df_latribune$Occurences)
# Divisions des occurences par l'écart type, ce qui nous donne un écart type unitaire
df_lesechos$Occurences <- (df_lesechos$Occurences) / sqrt(echos_var)
df_latribune$Occurences <- (df_latribune$Occurences) / sqrt(tribune_var)
# La normalisation de chaque série mensuelles des différents journaux nous permets de les combiner
# Création du dataframe qui va faire la somme des deux dataframes
df_france <- bind_rows(df_lesechos,df_latribune)
df_france <- df_france %>% group_by(Date) %>% summarise(Occurences = sum(Occurences)) %>% arrange(desc(Date))
# On divise par 2 la série obtenue car on a 2 sources d'informations
df_france$Occurences <- df_france$Occurences / 2
# Calcul de la moyenne de la série
moyenne <- mean(df_france$Occurences)
# On ramène la série à une moyenne de 100 afin d'obtenir l'indicateur EPU de chaque mois
df_france$Occurences <- df_france$Occurences*(100/moyenne)
# Visualisation de la série à l'aide ggplot2
p <- df_france %>%
ggplot(aes(x=Date, y=Occurences, text = paste0("Date : ", format(Date, "%Y-%m"), "\n",
"EPU : ", round(Occurences)))) +
geom_area(fill="#5685D7", alpha=0.5, group=1) +
geom_line(color="#FF0000", size=0.2, group=1) +
ggtitle("FR Indice EPU") +
ylab("EPU") +
xlab("Années-Mois") +
geom_point(size=0.5) +
scale_x_date(breaks = df_france$Date, labels = date_format("%Y-%m")) +
theme(axis.text.x = element_text(angle = 90),
plot.title = element_text(size=14, face="italic", family="Avenir Next"),
axis.title.x = element_text(family="Avenir Next"),
axis.title.y = element_text(family="Avenir Next"))
p <- ggplotly(p, tooltip = "text")
p
}
The object p is the graph.
i really don't know how to proceed in order to display the graph. When I run the app, only the sidebar is display, and there is no graph. I have any errors in the consol...
If someone can help me, it would be really great.
Thanks a lot !!!
Reading in the csv files on the server side might help. Try this
server <- function(input, output) {
# On importe les données du csv dans les dataframes
df_lesechosi <- read.csv(file = "data/df_lesechos.csv", sep=",")
df_latribunei <- read.csv(file = "data/df_latribune.csv", sep=",")
mygraph <- reactive({
graph_epu(df_lesechos=df_lesechosi, df_latribune=df_latribunei)
})
output$p <- renderPlotly({
mygraph()
})
}
### Your function should be as follows, and no need to read in csv files within this function
graph_epu <- function(df_lesechos="", df_latribune=""){...
Related
Recently I'm using the survival package in R, in order to be able to better measure the waiting time of patients in the Emergency Department of my Hospital, what I have achieved. However, it's complex to show the results and that can be understood by third parties from RStudio, so I'm developing a Shiny App to show the results without having to show the code and be able to modify certain elements quickly
When I create the app, I have the problem that when I request that you build a dataframe with the quantiles, I get the error: "Error in rep: invalid 'times' argument" in R#200. I have reviewed the code on multiple occasions, but I still can't find a solution. I enclose the complete code
Thank you
ui <- fluidPage(
titlePanel("Prototipo Tiempos de Urgencia"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "triage",
label = "Triage",
choices =c("Todos",listadotriage),
selectize = FALSE,
selected = "Todos"),
selectInput(inputId = "tiempo",
label = "Tiempo a analizar",
choices = c("Diferencia entre Hora de atención y hora de triage" = "60",
"Diferencia ente hora de atencón y hora de admisión" = "61",
"Diferencia ente hora de atencón y hora de alta" = "62",
"Diferencia ente hora de admision y hora de alta" = "63",
"Diferencia ente hora de admision y hora de triage" = "64"),
selectize = FALSE,
selected = "Diferencia entre Hora de atención y hora de triage"),
selectInput(inputId = "atencion",
label = "Área Atención",
choices = c("Todos",listadoatencion),
selectize = FALSE,
selected = "Todos"),
selectInput(inputId = "alta",
label = "Tipo de Alta",
choices = c("General" = "74",
"Hospitalizado" = "72",
"Altas" = "73"),
multiple = FALSE,
selected = "General"),
dateRangeInput(inputId = "fecha",
label = "Intervalo de fechas",
format = "dd-mm-yyyy",
start = "2019-11-01",
end = "2019-11-30",
weekstart = 1,
language= "es",
separator = "a")
),
mainPanel = dataTableOutput(outputId = "tabla1")
))
server <- function(input, output) {
output$tabla1 <- renderDataTable({
if (input$triage=="Todos") {
dat1<-subset(dat1,ifelse(input$atencion!="Todos",dat1$AREA_ATENCION==input$atencion & dat1$fechanormal>=input$fecha[1] & dat1$fechanormal<=input$fecha[2],
dat1$fechanormal>=input$fecha[1] & dat1$fechanormal<=input$fecha[2]))
timesevent<-as.integer(input$tiempo)
event<-as.integer(input$alta)
dat3<-dat1[,c(30,timesevent,event)]
gral<-Surv(dat3[[2]] ,event= as.numeric(dat3[[3]]))
fit1a<-survfit(gral ~ Medico, data = dat3)
d1<-as.data.frame(quantile(fit1a,c(0.25,0.5,0.75,0.9,1),conf.int = FALSE)) # estadísticas sobre tiempo de demora según modelo
data1<-as.data.frame(fit1a$strata)
setDT(data1,keep.rownames = TRUE)
data1$rn<-gsub("Medico=","",data1$rn)
colnames(data1)<-c("Médico","Consultas")
setDT(d1,keep.rownames = TRUE)[]
d1$rn<-gsub("Medico=","",d1$rn)
colnames(d1)<-c("Médico","P.25","P.50","P.75","P.90","P.100")
datatotal1<-merge(data1,d1,by="Médico")
datatable(data=datatota1l,caption =paste("Tiempos de atención en Servicio de Urgencia por Médico, por Atención en Servicio",input$atencion,"durante","el período",format(input$fecha[1], format= "%d-%m-%Y"),"a",format(input$fecha[2], format= "%d-%m-%Y"), sep=" "),
rownames = FALSE,extensions= "Buttons",options=list(pageLength=40,dom="Bfrtip", buttons = c("print")) )
} else {
dat1<-subset(dat1,dat1$Triage==input$triage)
dat1<-subset(dat1,ifelse(input$atencion!="Todos",dat1$AREA_ATENCION==input$atencion & dat1$fechanormal>=input$fecha[1] & dat1$fechanormal<=input$fecha[2],
dat1$fechanormal>=input$fecha[1] & dat1$fechanormal<=input$fecha[2]))
timesevent<-as.integer(input$tiempo)
event<-as.integer(input$alta)
dat3<-dat1[,c(30,timesevent,event)]
gral<-Surv(dat3[[2]] ,event= as.numeric(dat3[[3]])) ~ Medico
fit1b<-survfit(gral ~ Medico, data = dat3)
d2<-as.data.frame(quantile(fit1b,c(0.25,0.5,0.75,0.9,1),conf.int = FALSE)) # estadísticas sobre tiempo de demora según modelo
data2<-as.data.frame(fit1b$strata)
setDT(data2,keep.rownames = TRUE)
data2$rn<-gsub("Medico=","",data2$rn)
colnames(data2)<-c("Médico","Consultas")
setDT(d2,keep.rownames = TRUE)[]
d2$rn<-gsub("Medico=","",d2$rn)
colnames(d2)<-c("Médico","P.25","P.50","P.75","P.90","P.100")
datatotal2<-merge(data2,d1,by="Médico")
datatable(data=datatotal2,caption =paste("Tiempos de atención en Servicio de Urgencia por Médico, por Categorización",input$triage,"por Atención en Servicio",input$atencion,"durante","el período",format(input$fecha[1], format= "%d-%m-%Y"),"a",format(input$fecha[2], format= "%d-%m-%Y"), sep=" "),
rownames = FALSE,extensions= "Buttons",options=list(pageLength=40,dom="Bfrtip", buttons = c("print")) )
}
})
}
shinyApp(ui = ui, server = server)```
I resolved!!!!
I changed the next lines
dat1<-subset(dat1,ifelse(input$atencion!="Todos",dat1$AREA_ATENCION==input$atencion & dat1$fechanormal>=input$fecha[1] & dat1$fechanormal<=input$fecha[2],
dat1$fechanormal>=input$fecha[1] & dat1$fechanormal<=input$fecha[2]))
```
for the next lines:
```
dat3<-subset(dat3,dat3$fechanormal>=input$fecha[1] & dat3$fechanormal<=input$fecha[2])
ifelse(input$atencion!="Todos",dat3<-subset(dat3,dat3$AREA_ATENCION==input$atencion),NA)
```
Regards!!!
I´ve made a little simulator to teach the basics of population dynamics under stochasticity. This is a simple viz for the Ricker equation. It works in linux, however, I get a criptic error while running it under other environment (macos, win).
So, I wonder what my best options are to debug this error:
<simpleError in is.list(x): object of type 'closure' is not subsettable>
here is the code. I suspect on the plotly library in R... any hint?
# Ejercicio para ensenar curvas de crecimiento poblacional
# _author_ = horacio.samaniego#gmail.com
# _date_ = August 2018
# Check whether required packages are installed
list.of.packages <- c("manipulateWidget", "plotly")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
# librerias requeridas
library(manipulateWidget)
library(plotly)
# Simulador
crecLogistico <- function(t=80,r=1,n0=10,K=60,d=0){
# Simulacion de crecimiento poblacional con tasa de crecimiento (r) variable
# que simula variabilidad (estocasticidad ambiental)
# t, numero de generaciones a simular
# r, tasa intrinsica de crecimiento
# n0, abundancia inicial
# K, capacidad de carga
# d, estocasticidad
N <- matrix(n0,ncol=t,nrow=1) # vector con tamano poblacional (abundancia) inicial
R <- matrix(NA,ncol=t,nrow=1) # vector con tasas de crecimiento
for(i in 1:t) {
if(d>0) R[i] <- rnorm(1,mean=r,sd=d) else R[i] <- r
# N[i+1] <- N[i]+N[i]*R[i]*(1-N[i]/K) # Logistica
N[i+1] <- N[i]*exp(R[i]*(1 - N[i]/K)) # Ricker
}
res <- matrix(c(1:t,N[-(t+1)],R),ncol=3)
res <- as.data.frame(res)
names(res) <- c("t","Abundancia","r")
return(res)
}
## Plot de Crecimiento Logistico
if ( require(plotly) ) {
manipulateWidget({
# Modela abundancias
res = crecLogistico(n0=n0,t=t,r=r,K=K,d=d)
# Colecta informacion para construir mapa logistico
mapa = data.frame("N_1"=res$Abundancia[-t],"N_0"=res$Abundancia[-1])
combineWidgets( # crea ventanas donde plotear (proporcion 3:1). Una grande a la izq y otra con 2 lineas a la dcha (1:1)
ncol = 2,colsize=c(3,1),
# Evolucion temporal de poblacion
p = plot_ly(res[rango[1]:rango[2],],x=~t,y=~Abundancia,type="scatter",
mode="lines+markers",line=~r,color=~r), # %>%
# agrega linea para remarcar abundancia = 0
add_segments(p, x = rango[1], xend = rango[2], y = 0, yend = 0,mode="lines") %>%
# muestra escocasticidad a cada tiempo segun color
colorbar(title="Tasa de Crecimiento") %>%
layout(title="Crecimiento Logistico",showlegend = FALSE,yaxis=list(zerolinecolor=toRGB("red"))),
combineWidgets(
ncol = 1,
# histograma de estocasticidad a lo largo de todo el tiempo
plot_ly(res,x=~r,type="histogram") %>%
layout(title="Tasa de Crecimiento"),
# mapa logistico, muestra estados estacionarios en primer orden, de t-a a t
plot_ly(mapa,x=~N_1,y=~N_0,type="scatter",mode="markers") %>%
add_segments(x=0,xend=max(res$Abundancia),y=0,yend=max(res$Abundancia)) %>%
layout(title="Mapa Logistico", xaxis = list(title = "abundancia (t)"),
yaxis = list(title="abundancia (t-1)"))
)
)
},
n0 = mwNumeric(100, min = 2, step = 1 , label = "Poblacion Inicial"),
t = mwNumeric(100, min = 2, step = 1 , label = "Generaciones (t)"),
r = mwNumeric(0.9, min = -4, step = 0.05 , label = "Tasa de Crecimiento (r)"),
K = mwNumeric(60, min = 5, step = 2, label = "Capacidad de Carga"),
d = mwNumeric(0.05, min = 0, step = 0.05 ,label = "Estocasticidad"),
rango = mwSlider(0, t, c(1, t),label="Generaciones a Visualizar")
)
}
will report... thanks a bunch!!
Ok, I've got the issue... the problem is that plotly in R (or rstudio) for linux is not too picky about the 'line' flag in plot_ly, which macos strictly enforces.
I unfortunately have no training in debugging code and would not be able diagnose this using the standard tools mentioned here (will learn though!)
recasting the line to this:
plot_ly(res[rango[1]:rango[2],],x=~t,y=~Abundancia,type="scatter", mode="lines+markers",color=~r) %>%
did all the trick.
Thanks,
I'll copy my equation explorer here just in case:
# Ejercicio para ensenar curvas de crecimiento poblacional
# _author_ = horacio.samaniego#gmail.com
# _date_ = August 2018
# Check whether required packages are installed
list.of.packages <- c("manipulateWidget", "plotly")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
# librerias requeridas
library(manipulateWidget)
library(plotly)
# Simulador
crecLogistico <- function(t=80,r=1,n0=10,K=60,d=0){
# Simulacion de crecimiento poblacional con tasa de crecimiento (r) variable
# que simula variabilidad (estocasticidad ambiental)
# t, numero de generaciones a simular
# r, tasa intrinsica de crecimiento
# n0, abundancia inicial
# K, capacidad de carga
# d, estocasticidad
N <- matrix(n0,ncol=t,nrow=1) # vector con tamano poblaciona (abundancia) inicial
R <- matrix(NA,ncol=t,nrow=1) # vector con tasas de crecimiento
for(i in 1:t) {
if(d>0) R[i] <- rnorm(1,mean=r,sd=d) else R[i] <- r # adds stochasticity
# N[i+1] <- N[i]+N[i]*R[i]*(1-N[i]/K) # Logistica
N[i+1] <- N[i]*exp(R[i]*(1 - N[i]/K)) # Ricker
}
res <- matrix(c(1:t,N[-(t+1)],R),ncol=3)
res <- as.data.frame(res)
names(res) <- c("t","Abundancia","r")
return(res)
}
## Plot de Crecimiento Logistico
if ( require(plotly) ) {
manipulateWidget({
# Modela abundancias
res = crecLogistico(n0=n0,t=t,r=r,K=K,d=d)
# Colecta informacion para construir mapa logistico
mapa = data.frame("N_1"=res$Abundancia[-t],"N_0"=res$Abundancia[-1])
combineWidgets( # crea ventanas donde plotear (proporcion 3:1). Una grande a la izq y otra con 2 lineas a la dcha (1:1)
ncol = 2,colsize=c(3,1),
# Evolucion temporal de poblacion
plot_ly(res[rango[1]:rango[2],],x=~t,y=~Abundancia,type="scatter", mode="lines+markers",color=~r) %>%
# # muestra escocasticidad a cada tiempo segun color
colorbar(title="Tasa de Crecimiento") %>%
layout(title="Crecimiento Logistico",showlegend = FALSE,yaxis=list(zerolinecolor=toRGB("red"))),
combineWidgets(
ncol = 1,
# histograma de estocasticidad a lo largo de todo el tiempo
plot_ly(res,x=~r,type="histogram") %>%
layout(title="Tasa de Crecimiento"),
# mapa logistico, muestra estados estacionarios en primer orden, de t-a a t
plot_ly(mapa,x=~N_1,y=~N_0,type="scatter",mode="markers") %>%
add_segments(x=0,xend=max(res[[2]]),y=0,yend=max(res[[2]])) %>%
layout(title="Mapa Logistico", xaxis = list(title = "abundancia (t)"),
yaxis = list(title="abundancia (t-1)"),showlegend = FALSE)
)
)
},
n0 = mwNumeric(100, min = 2, step = 1 , label = "Poblacion Inicial"),
t = mwNumeric(100, min = 2, step = 1 , label = "Generaciones (t)"),
r = mwNumeric(0.9, min = -4, step = 0.05 , label = "Tasa de Crecimiento (r)"),
K = mwNumeric(60, min = 5, step = 2, label = "Capacidad de Carga"),
d = mwNumeric(0.05, min = 0, step = 0.05 ,label = "Estocasticidad"),
rango = mwSlider(0, t, c(1, t),label="Generaciones a Visualizar")
)
}
I am new to Dygraph in R, that I use to plot my data (with xts). Everything is OK, it works well.
But the problem is: I'm not able to use axisLabelFormatter for making labels bold and bigger. How is that possible?
Further, can I add a frame around the chart (like the black line of x and y axis)?
The image here explain my 2 questions: click here for example image
Below is the code I am trying:
library(shiny)
library(dygraphs)
library(xts)
#------Importation des données contenues dans un .csv------
setwd("C:/Users") #attention,on ne peut pas faire créer à R un dossier, il faut le créer via windows
#----Importation données de qualité d'eau
TabSMP=read.csv2(file="Analyse R/MC1_MC2_SMP.csv",sep=";",dec=".",na.strings = "#N/A")
TabSMPMC1=read.csv2(file="Analyse R/MC1_SMP.csv",sep=";",dec=".",na.strings = "#N/A")
TabSMPMC2=read.csv2(file="Analyse R/MC2_SMP.csv",sep=";",dec=".",na.strings = "#N/A")
TabMC1Manu=read.csv2(file="Analyse R/MC1_Manu.csv",sep=";",dec=".",na.strings = "#N/A")
TabMC2Manu=read.csv2(file="Analyse R/MC2_Manu.csv",sep=";",dec=".",na.strings = "#N/A")
TabMC3Manu=read.csv2(file="Analyse R/MC3_Manu.csv",sep=";",dec=".",na.strings = "#N/A")
TabMC4Manu=read.csv2(file="Analyse R/MC4_Manu.csv",sep=";",dec=".",na.strings = "#N/A")
#-----Attribution du format de date et heure à la colonne date/heure pour chaque tableau------
TabSMP$DateHeure=as.POSIXct(TabSMP$DateHeure,format="%d/%m/%Y %H:%M")
TabSMPMC1$DateHeure=as.POSIXct(TabSMP$DateHeure,format="%d/%m/%Y %H:%M")
TabSMPMC2$DateHeure=as.POSIXct(TabSMP$DateHeure,format="%d/%m/%Y %H:%M")
TabMC1Manu$DateHeure=as.POSIXct(TabMC1Manu$Date,format="%d/%m/%Y %H:%M")
TabMC2Manu$DateHeure=as.POSIXct(TabMC2Manu$Date,format="%d/%m/%Y %H:%M")
TabMC3Manu$DateHeure=as.POSIXct(TabMC3Manu$Date,format="%d/%m/%Y %H:%M")
TabMC4Manu$DateHeure=as.POSIXct(TabMC4Manu$Date,format="%d/%m/%Y %H:%M")
#TabB5Manu$DateHeure=as.POSIXct(TabB5Manu$Date,format="%d/%m/%Y %H:%M")
ls.str()# vérification des reconnaissances par R des caractères numériques, textes, dates...
TabSMPMC1_xts_Temp <- xts(TabSMP$MC1_Temp,order.by=TabSMP$DateHeure,frequency=365)
TabSMPMC2_xts_Temp <- xts(TabSMP$MC2_Temp,order.by=TabSMP$DateHeure,frequency=365)
TabMC3Manu_xts_Temp <- xts(TabMC3Manu$MC3_Temp,order.by=TabMC3Manu$DateHeure,frequency=365)
TabMC4Manu_xts_Temp <- xts(TabMC4Manu$MC4_Temp,order.by=TabMC4Manu$DateHeure,frequency = 365)
Temperature <- cbind(TabSMPMC1_xts_Temp,TabSMPMC2_xts_Temp,TabMC3Manu_xts_Temp,TabMC4Manu_xts_Temp)
dygraph(Temperature,main="Evolution de la tempértaure") %>%
dyAxis("y", label = "°C ", valueRange = c(-1, 11)) %>%
dySeries("..1",label="MC1_Temp",strokeWidth=1.75) %>%
dySeries("..2",label="MC2_Temp",strokeWidth=1.75) %>%
dySeries("..3",label="MC3_Temp",pointSize=2.5) %>%
dySeries("..4",label="MC4_Temp",pointSize=2.5) %>%
dyOptions(colors = c("blue","orange","pink","green")) %>%
dyLegend(width=400) %>%
dyEvent(DebutVidange, "Ouverture Vanne de Fond", labelLoc = "top") %>%
dyEvent(FinVidange, "Fin Vidange", labelLoc = "top") %>%
dyShading(from =DebutVidange, to =FinVidange, color = "#F0F9FF") %>%
dyShading(from =DebutAssec, to =FinAssec, color = "#FFFFFF") %>%
dyRangeSelector()
try this:
dyAxis(
"y",
axisLabelFormatter = 'function(d){return d.toString().fontsize(4);}', # makes them bigger
axisLabelWidth = 70
) %>%
and change the fontsize(4) to other numbers. An for bold tage the line: axisLabelFormatter = 'function(d){return d.toString().fontsize(4).bold();}',
as:
dygraph(Temperature,main="Evolution de la tempértaure") %>%
dyAxis("y", label = "°C ", valueRange = c(-1, 11)) %>%
dySeries("..1",label="MC1_Temp",strokeWidth=1.75) %>%
dySeries("..2",label="MC2_Temp",strokeWidth=1.75) %>%
dySeries("..3",label="MC3_Temp",pointSize=2.5) %>%
dySeries("..4",label="MC4_Temp",pointSize=2.5) %>%
dyOptions(colors = c("blue","orange","pink","green")) %>%
dyLegend(width=400) %>%
dyEvent(DebutVidange, "Ouverture Vanne de Fond", labelLoc = "top") %>%
dyEvent(FinVidange, "Fin Vidange", labelLoc = "top") %>%
dyShading(from =DebutVidange, to =FinVidange, color = "#F0F9FF") %>%
dyShading(from =DebutAssec, to =FinAssec, color = "#FFFFFF") %>%
dyAxis(
"y",
axisLabelFormatter = 'function(d){return d.toString().fontsize(4);}', # makes them bigger
axisLabelWidth = 70
) %>%
dyRangeSelector()
I got also the x-axis, but it chages to numbers: 2017.3 etc, note that you need to add 1 to months since months Jan-Dec are 0-11 in Javascript, here:
dyAxis(
"x",
# label = "Number",
axisLabelFormatter = 'function(d){ var month = (d.getMonth() +1).toString().fontsize(3) ;var year = d.getFullYear().toString().fontsize(3); return year + "."+ month}', ## + 1 since months jan-dec are 0-11 in Javascript
axisLabelFontSize = 20,
axisLabelWidth = 70 ## gets them apart, but not bigger
) %>%
I just discovered rChart and googleVis and i want to thank developers for their job.
My problem is simple, i want to add a variable label to my axis for nplot?
I also want to know if it's possible to add variable like sizevar and colorvar of gvisBubbleChart to nplot ?
Thank you.
library(rCharts)
VehiculeFunction <- function(data, gamme, absciss, ordinate){
# Aim: Permet de visualiser les données sous la forme de nuages de points
# croisant GMF*Coût, Ratio K * Ratio Coût ou bien GMF*Ratio en
# choisissant la gamme qu'on désire
# Input: data.frame avec notamment GAMME, PROJET, PERIMETRE, NITG, GMF.24,
# Cout.24 et libele
# Output: Graphique avec le croisement choisi ainsi que le libellé étiquetté
# sur le point qu'on voudra identifier
if(absciss == "GMF.24"){
my.data <- data[data$RANG_NITG_PROJET_K %in% c(1, 2, 3),]
} else if(absciss == "Ratio.K") {
my.data <- data[data$RANG_NITG_PROJET_C %in% c(1, 2, 3),]
}
my.data2 <- my.data[my.data$GAMME == gamme,]
X <- my.data2[[absciss]]
Y <- my.data2[[ordinate]]
SIZEVAR <- my.data2$Ratio.K
df <- data.frame(X,Y,SIZEVAR)
plot <- nPlot(x = "X", y = "Y", size = "SIZEVAR", data = df, type = "scatterChart")
plot$xAxis(axisLabel = 'X')
plot
}
VehiculeFunction(data.vehicule, gamme = "M1", "GMF.24", "Cout.24")
Usage:
gvisBubbleChart(data, idvar = "", xvar = "", yvar = "",
colorvar = "", sizevar = "",
options = list(), chartid)
E.G.
## Set color and size
bubble2 <- gvisBubbleChart(Fruits, idvar="Fruit", xvar="Sales", yvar="Expenses",
colorvar="Location", sizevar="Profit",
options=list(hAxis='{minValue:75, maxValue:125}'))
SEE http://www.inside-r.org/packages/cran/googleVis/docs/gvisBubbleChart
I need help about this function, i try it with plot (R) and googleVis, it works perfectly; now i want to use rChart but when i launch the functions it returned me a simple grid with no points on it.
VehiculeFunction <- function(data, gamme, absciss, ordinate){
# Aim: Permet de visualiserles données sous la forme de nuages de points
# croisant GMF*Coût, Ratio K * Ratio Coût ou bien GMF*Ratio en
# choisissant la gamme qu'on désire
# Input: data.frame avec notamment GAMME, PROJET, PERIMETRE, NITG, GMF.24,
# Cout.24 et libele
# Output: Graphique avec le croisement choisi ainsi que le libellé étiquetté
# sur le point qu'on voudra identifier
if(absciss == "GMF.24"){
my.data <- data[data$RANG_NITG_PROJET_K %in% c(1, 2, 3),]
} else if(absciss == "Ratio.K") {
my.data <- data[data$RANG_NITG_PROJET_C %in% c(1, 2, 3),]
}
my.data2 <- my.data[my.data$GAMME == gamme,]
X <- my.data2[[absciss]]
Y <- my.data2[[ordinate]]
plot <- nPlot(Y ~ X, data = data, type = 'scatterChart')
plot
}
VehiculeFunction(data.vehicule2, gamme = "M1", "GMF.24", "Cout.24")
data.vehicule2 is a dataframe.
Thank you.
EDIT:
In the dataframe, i have 18 variables and 36 000. This code works perfectly, but my problem is the plot appearance.
library(rCharts)
VehiculeFunction <- function(data, gamme, absciss, ordinate){
# Aim: Permet de visualiser les données sous la forme de nuages de points
# croisant GMF*Coût, Ratio K * Ratio Coût ou bien GMF*Ratio en
# choisissant la gamme qu'on désire
# Input: data.frame avec notamment GAMME, PROJET, PERIMETRE, NITG, GMF.24,
# Cout.24 et libele
# Output: Graphique avec le croisement choisi ainsi que le libellé étiquetté
# sur le point qu'on voudra identifier
if(absciss == "GMF.24"){
my.data <- data[data$RANG_NITG_PROJET_K %in% c(1, 2, 3),]
} else if(absciss == "Ratio.K") {
my.data <- data[data$RANG_NITG_PROJET_C %in% c(1, 2, 3),]
}
my.data2 <- my.data[my.data$GAMME == gamme,]
X <- my.data2[[absciss]]
Y <- my.data2[[ordinate]]
SIZEVAR <- my.data2$Ratio.K
df <- data.frame(X,Y,SIZEVAR)
plot <- nPlot(x = "X", y = "Y", size = "SIZEVAR", data = df, type = "scatterChart")
plot
}
VehiculeFunction(data.vehicule, gamme = "M1", "GMF.24", "Cout.24")
Could i add a size variable because on the plot nothing appears, how could i have my variable "GMF.24" and "Cout.24" on the axis ? and the last question, is it possible to add label when i place the mouse above a point ?
Thank you in advance.