R中的图例帮助

时间:2015-03-27 16:55:58

标签: r graph

所以我想在笔记中添加一些图表。我已经创建了一个简单的兴趣函数,它将使用不同的速率绘制几个简单的兴趣函数,我想添加一个简单的说法...... " i =:0%,x%,y%,z%"在一条线上,其中每个0,x,y,z使用该利率处于代表函数的不同颜色。

我查看了paste()函数并尝试将其设为一个字符串,但我不确定如何将其循环到int_seq并拉出每个索引并使其成为不同的颜色然后将其放入单个字符串中

# indexs to be used
t = 0:50
int_seq = seq(0.025,0.10,by=0.025)  # intere rate sequence
colors = c("red","blue","green","orange")   #colors of interest rate seq
index = 1:length(int_seq)

# AV Simple Interest  (all good)
avSimple = function(i,t){
av = (1 + (i * t))
return(av)}

# Plot range for y-axis   (all good)
yrange = c(avSimple(min(int_seq),min(t)) * 0.95,
avSimple(max(int_seq),max(t)) * 1.05)

# Plots Simple Interest with different interest rates (all good)
plot(t,avSimple(0,t), type="l", main = "AV Simple Interest", xlab = "Time",
ylab = "AV", ylim = yrange)
# loops through the int_seq and plots line based on interest rate
# and specified color  (all good)
for (i in index) 
lines(t,avSimple(int_seq[i],t), col = colors[i])

# Adds legend to plot for different interest rates
# !!This is where I need the help, not sure best way to approach!!
legend(0,avSimple(0.075,50), c("i =: 0%", for (i in index) int_seq[i]), 
col = colors)

1 个答案:

答案 0 :(得分:0)

不确定你想要什么样的传奇。由于您在一行中说,您可能想要添加horiz = TRUE,但这里有一些其他选项:

您可以将完整向量传递给legend,因此在这种情况下不需要循环。只需创建一个标签矢量,但也可以使用与每个标签相对应的颜色矢量(您已经完成)。

# indexs to be used
t = 0:50
int_seq = seq(0.025,0.10,by=0.025)  # intere rate sequence
colors = c("red","blue","green","orange")   #colors of interest rate seq
index = 1:length(int_seq)

# AV Simple Interest  (all good)
avSimple = function(i,t){
  av = (1 + (i * t))
  return(av)}

# Plot range for y-axis   (all good)
yrange = c(avSimple(min(int_seq),min(t)) * 0.95,
           avSimple(max(int_seq),max(t)) * 1.05)


plot(t, type="n", main = "AV Simple Interest", xlab = "Time",
     ylab = "AV", ylim = yrange)
# for (i in index) 
#   lines(t,avSimple(int_seq[i],t), col = colors[i])

# Adds legend to plot for different interest rates
# !!This is where I need the help, not sure best way to approach!!

labs <- sprintf('i =: %s%%', c(0, int_seq))
labs2 <- paste0(c(0, int_seq), '%')


legend('topleft', legend = labs, col = colors, lty = 1, title = 'normal')

l <- legend('top', legend = rep('i =:', length(labs)), lty = 1,
            col = colors, text.width = max(strwidth(labs)) + 1, 
            title = 'right-justified')
text(l$rect$left + l$rect$w, l$text$y, labs2, pos = 2)

legend('topright', legend = labs, text.col = colors, title = 'colored')

legend('bottom', legend = labs, col = colors, lty = 1, horiz = TRUE,
       cex = .7, title = 'horizontal')

enter image description here