R & ggplot2: Sparklines from dynamic variables (based on query results)
I've written an SQL query that tells me the names of the previous week's top 10 most frequent Alarms. And I've written a query that takes those top 10 alarms and provides a YTD weekly totals for each of those alarms.
Now I'm looking to create a panel of sparklines showing the YTD trend for each of the week's top 10 alarms.
I got something resembling what I'd like, but I now need to make it "dynamic". i.e. to make it work without hardcoding the names of the alarms (since these will change with the SQL query every week).
How can I go about changing the R code below to work without hardcoding the names of the alarms?
Does levels(spark$Alarm) have something to do with?
Thanks kindly for the advice :-)
Week = c(rep(1:8,2))
Total = rnorm(16,1000,600)
Alarm = c(rep("BELTWEIGHER HIGH HIGH",8), rep("MICROWAVE LHS",8))
spark <- data.frame(Week, Alarm, Total)
s <- ggplot(spark, aes(Week, Total)) +
facet_grid(Alarm ~ ., scales = "free", as.table = FALSE) +
opts(
panel.background = theme_rect(size = 1, colour = "lightgray"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
axis.line = theme_blank(),
axis.text.x = theme_blank(),
axis.text.y = theme_blank(),
axis.title.x = theme_blank(),
axis.title.y = theme_blank(),
axis.ticks = theme_blank(),
strip.background = theme_blank(),
strip.text.y = theme_text(size = 7, colour = "red", angle = 90)
)
s1 <- s + geom_line(subset = .(Alarm == "BELTWEIGHER HIGH HIGH"))
s2 <- s1 + geom_line(subset = .(Alarm == "MICROWAV开发者_Python百科E LHS"))
s2
Okay that was a dumb question :)
Here's the obvious answer.
Week = c(rep(1:8,2))
Total = rnorm(16,1000,600)
Alarm = c(rep("BELTWEIGHER HIGH HIGH",8), rep("MICROWAVE LHS",8))
spark <- data.frame(Week, Alarm, Total)
s <- ggplot(spark, aes(Week, Total)) +
theme(
panel.background = element_rect(size = 1, colour = "lightgray"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.ticks = element_blank(),
strip.background = element_blank(),
strip.text.y = element_blank()
#strip.text.y = element_text(size = 7, colour = "red", angle = 90)
)
s + facet_grid(Alarm ~.) + geom_line()
精彩评论