rrmysql

Using database column names as axis names for r plot


I am extracting data from a database using RMySQL and then using this data to plot a graph.

The code I currently have is as follows:

con <- dbConnect(dbDriver('MySQL'), user = 'root', password = 'root', dbname='dbname')
df <- data.frame(dbGetQuery(con, paste('select * from test')))
plot(df$ID, df$UID, xlab='test1', ylab='test2', type='l')

This works absolutely fine but my question is how can I use the DB column name as the axis labels instead of hard coding the labels in?


Solution

  • To use the names of the data frame that come from the data base use names(df) or if they are rownames use rownames(df).

    Then you can subset to one value, example, assuming that the names are in the column and the ID is the first column and the UID the second.

    plot(df$ID, df$UID, xlab=names(df)[1], ylab=names(df)[2], type='l')