Skip to content

Instantly share code, notes, and snippets.

@jacoby
Last active December 13, 2015 21:48
Show Gist options
  • Save jacoby/4979796 to your computer and use it in GitHub Desktop.
Save jacoby/4979796 to your computer and use it in GitHub Desktop.
From Database to exported PNG with R.
require( sqlutils )
require( RMySQL )
library( Cairo )
library( yaml )
my.cnf = yaml.load_file( '~/.my.yaml' )
default = my.cnf$clients$default
p_cols <- c( "blue" , "red" , "orange" , "green" )
con <- dbConnect(
MySQL(),
user=default$user ,
password=default$password,
dbname=default$database,
host=default$host
)
rs <- dbSendQuery(
con ,
'
SELECT TIME_FORMAT( time , "%l %p" ) time
, AVG( temp_f ) temperature
FROM weather
WHERE HOUR( TIMEDIFF( SYSDATE() , TIME ) ) < 24
GROUP BY HOUR( time )
ORDER BY HOUR( TIMEDIFF( SYSDATE() , TIME ) )
DESC;
'
)
fields = dbColumnInfo(rs)
data_frame = fetch(rs, n = 24 )
time = data_frame[[ "time" ]]
temp = data_frame[[ "temperature" ]]
CairoPNG(
filename="/path/to/where/i/write/test.png" ,
width = 500 ,
height = 500 ,
pointsize = 9
)
plot ( temp
, main="Temperatures for the last 24 Hours"
, sub="West Lafayette, IN - Temperatures in Fahrenheit"
, col=p_cols[2]
, type="l"
, xlab="Time"
, ylab="Temperature(F)"
, xaxt='n'
)
axis( 1 , las=2 , at=1:24 , lab=time )
box()
@jacoby
Copy link
Author

jacoby commented Feb 19, 2013

Changed the code to read a modified .my.cnf file called .my.yaml which holds the client configuration. This means that my password info gets out of the script. Yay!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment