从数据集创建基础图

时间:2017-10-07 00:30:43

标签: r plot dataset

我需要得到如下图所示的结果:

https://drive.google.com/file/d/0B4Mldbnr1-avMFgzS1Y4d2lqYUk/view?usp=sharing

我从以下链接获得了数据集:

https://drive.google.com/file/d/0B4Mldbnr1-avLUg1REJRRzFUZU0/view?usp=sharing

这是我到目前为止编写的代码,但似乎不正确:

source("load_data.R")

plot1 <- function(data=NULL) {
  if(is.null(data))
    data <- load_data()

library(datasets)
library(ggplot2)  
with(data, plot(Voltage,Global_active_power,type="n"))
with(subset(data, Voltage>=250), points(Voltage,Global_active_power, col="black"))
with(subset(data, Voltage!=249), points(Voltage,Global_active_power, col="red"))
title(main="Global Active Power(Kilowatts) for Voltage >=249")
legend("topright", pch = 1, col=c("black","red"), legend = c("Voltage>=249 & <250","Voltage>=250"))

}

我正在针对GLobal_active_power数据绘制电压数据,如图中所示,仅电压&gt; = 249

请提前帮助我,谢谢你

1 个答案:

答案 0 :(得分:0)

假设dat是数据集,请尝试

clr <- ifelse(dat[,"Voltage"]<250, "black", "red")
plot(Global_active_power ~ Voltage, data=dat, col=clr, xlim=c(249,252))
legend("topright", legend=c("<250", ">=250"), col=clr, pch=1)

稍微改变以匹配预期结果:

clr <- ifelse(data[,"Voltage"]<250, "black", "red")
plot(Global_active_power ~ Voltage, data=data, col=clr, xlim=c(249,252))
legend("topright", pch = 1, col=c("black","red"), legend = c("Voltage>=249 & <250","Voltage>=250"))
title(main="Global Active Power(Kilowatts) for Voltage >=249")