繁体   English   中英

使用R将图例添加到绘图中

[英]Add legend to a plot with R

我使用R在一个图中创建了4行。 这里的代码

# Define 2 vectors
cars <- c(123.07, 110.51, 96.14, 98.71, 101.3)
trucks <- c(110.31, 89.91, 89.81, 89.31, 93.4, 95.81)
cars1 <- c(123.227, 110.221, 93.14, 98.22, 122.3)
trucks1 <- c(120.31, 89.91, 89.81, 89.31, 93.4, 95.81)
# Graph cars using a y axis that ranges from 0 to 12
plot(cars, type="o", col="blue", ylim=c(80,130))

# Graph trucks with red dashed line and square points
lines(trucks, type="o", pch=22, lty=2, col="red")
lines(cars1, type="o", col="yellow", ylim=c(80,130))

# Graph trucks with red dashed line and square points
lines(trucks1, type="o", pch=22, lty=2, col="green")
# Create a title with a red, bold/italic font
title(main="Autos", col.main="red", font.main=4)

我想知道如何在图中为每个图(线)添加图例。

谢谢

legend( "topleft", c("cars", "trucks", "cars1", "trucks1"), 
text.col=c("blue", "red", "yellow", "green") )

使用?legend命令查看选项,图表上的其他位置,“topleft”或文本大小,是否在图例周围有一个框等。

例如

legend(
  "topright", 
  lty=c(1,2,1,2), 
  col=c("blue", "red", "yellow", "green"), 
  legend = c("cars", "trucks", "cars1", "trucks1")
)

?legend

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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