简体   繁体   中英

How to visualize a multiline graphic in R?

I have the folloing R code which visualizes a multiline graph where each line corresponds to a category of data. In the code the categories are given my the variable nk: My dataset looks like this :

k   precision   recall
0.25    0.02    1.011
0.25    0.04    1.011
0.5 0.15    0.941
0.5 0.17    0.931
0.5 0.18    0.921
0.5 0.19    0.911
1.0 0.36    0.831
1.0 0.39    0.811
1.0 0.41    0.801

The problem is that it only visualizes the lines for k = 1.0 and not the lines for k = 0.5 and 0.25 My question is ? How can i use a nk variable which is not an integer in order to visualize lines for k = 0.5 or 0.25?

dtf$k <- as.numeric(dtf$k)
nk <- max(dtf$k)
xrange <- range(dtf$precision)
yrange <- range(dtf$recall)
plot(xrange, yrange,
 type="n",
 xlab="Precision",
 ylab="Recall"
 )
colors <- rainbow(nk)
linetype <- c(1:nk)
plotchar <- seq(18, 18+nk, 1)
for (i in 1:nk) {
 Ki <- subset(dtf, k==i)
 lines(Ki$precision, Ki$recall,
 type="b",
 lwd=2,
 lty=linetype[i],
 col=colors[i],
 pch=plotchar[i]
 )
}
title("Methods varying K", "Precision Recall")
legend(xrange[1], yrange[2],
 1:nk,
 cex=1.0,
 col=colors,
inset=c(-0.2,0),
 pch=plotchar,
 lty=linetype,
 title="k"
) 

Data

    dtf <- read.table(header = TRUE, text = 'k   precision   recall
0.25    0.02    1.011
0.25    0.04    1.011
0.5 0.15    0.941
0.5 0.17    0.931
0.5 0.18    0.921
0.5 0.19    0.911
1.0 0.36    0.831
1.0 0.39    0.811
1.0 0.41    0.801')
dtf$k <- factor(dtf$k)

ggplot2 solution

require(ggplot2)
ggplot(dtf, aes(x = precision, y = recall, col = k)) +
  geom_line()

base solution

plot(recall ~ precision, data = dtf, type = 'n')
cols = c('red', 'blue', 'green')
levs <- levels(df$k)
for(i in seq_along(levs)){
  take <- df[df$k == levs[i], ]
  lines(take$precision, take$recall, col = cols[i])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM