R中的图例水平图形间距

时间:2015-03-28 21:54:44

标签: r graph

好的,所以我之前就问过这个问题,虽然我现在已经取得了很多进展,但我不确定如何在旧帖子的评论中添加代码。无论如何这是我的新问题。我正在使用legend命令创建一个水平的leged,我希望有一种方法可以减少图例项目列表之间的空间

# initial variables, this is fine
t = 0:50
int_seq = seq(0,0.1,by=0.025)
int_seq100 = 100 * int_seq
colors = c("black","red","blue","green","orange")
index = 1:length(int_seq)

#AV Simple Interest, this is fine
avSimple = function(i,t){
    av = (1 + (i * t))
    return(av)}

# Plot range for y-axis, this is fine
yrange = c(avSimple(min(int_seq),min(t)) * 0.95,
    avSimple(max(int_seq),max(t)) * 1.15)

# Plots Simple Interest with different interest rates, this is fine
plot(t,avSimple(int_seq[1],t), type="l", 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
# where the trouble is
# ? And how can I reduce distance between each index in the labs string
# so it is only a space or two apart from each other
labs = c("i =:",sprintf('%s%%', c(int_seq100)))
legend('topleft', legend = labs, text.col = c("black",colors), 
    horiz = TRUE, bty = "n")

2 个答案:

答案 0 :(得分:2)

数据

t = 0:50

int_seq = seq(0,0.1,by=0.025)

colors = c("black","red","blue","green","orange")

mydf <- data.frame(rep(NA, length(t)), stringsAsFactors = FALSE)

for(i in int_seq){   mydf <- cbind(mydf, data.frame(1+(i*t), stringsAsFactors = FALSE)) }

mydf <- mydf[, 2:ncol(mydf)]

colnames(mydf) = paste(int_seq*100, "%", sep = "")

绘制数据框中的行

matplot(mydf, type = "l", col = colors, lty = 1, lwd = 2)

legend('topleft', lty = 1, lwd = 2,  legend = colnames(mydf), text.col = colors, horiz = TRUE, bty = "n", cex = 0.75, col = colors)

从数据框中绘制点

matplot(mydf, type = "p", col = colors, pch = c(seq(20, along.with = colnames(mydf))))

legend('topleft', legend = colnames(mydf), text.col = colors, box.col = "black", horiz = FALSE, bty = "o", cex = 0.75, col = colors, pch = c(seq(20, along.with = colnames(mydf)))) 

绘制数据框中的点和线

matplot(mydf, type = "p", col = colors, pch = c(seq(20, along.with = colnames(mydf))))

for(i in 1:ncol(mydf)){lines(mydf[,i], col = colors[i])}

legend('topleft', lty = 1, lwd = 2,  legend = colnames(mydf), text.col = colors, horiz = TRUE, bty = "n", cex = 0.75, col = colors, pch = c(seq(20, along.with = colnames(mydf))))

答案 1 :(得分:1)

text.width评论可以做到这一点。你需要玩这些数字。我也改为更小的字体大小(cex)并将所有数字设置为2位小数(sprintf)。应使用以下内容更改脚本中的最后几行:

labs = c("i =:",sprintf('%.2f', c(int_seq100)))
legend('topleft', text.width=c(0.3, 0.3, 0.3, 0.3, 0.3), cex = 0.75, legend = labs, text.col = c("black",colors), 
horiz = TRUE, bty = "n")

enter image description here