使用R语言进行实战:绘制图例
在数据可视化中,图例是一种重要的元素,它用于解释和说明图表中不同部分的含义。在R语言中,我们可以通过简单的代码来添加和自定义图例。
首先,让我们创建一些示例数据来绘制图表。假设我们正在分析一个销售数据集,其中包含三个产品的销售额和月份。我们将使用这些数据来创建一个折线图,并添加一个图例,以说明每个产品的含义。
# 创建示例数据
sales_data <- data.frame(
Month = c("Jan", "Feb", "Mar", "Apr", "May", "Jun"),
Product1 = c(120, 150, 180, 130, 160, 140),
Product2 = c(90, 100, 110, 120, 130, 140),
Product3 = c(80, 70, 90, 100, 95, 110)
)
# 绘制折线图
plot(x = sales_data$Month, y = sales_data$Product1,
type = "l", col = "blue", lwd = 2,
xlab = "Month", ylab = "Sales",
main = "Monthly Sales by Product")
# 添加其他两个产品的折线图
lines(x = sales_data$Month, y = sales_data$Product2,
type = "l", col = "red", lwd = 2)
lines(x = sales_data$Month, y = sales_data$Product3,