链接到数据集,这是一个日期和时间列以及用电列 https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip
power1 <- read.csv(file = "c:/datasets/household_power_consumption.txt", stringsAsFactors=F, header = TRUE,
sep=";", dec = ".", na.strings="?", col.names = c("date1","time1","Global_active_power", "Global_reactive_power",
"Voltage","Global_intensity","Sub_metering_1","Sub_metering_2",
"Sub_metering_3"))
power1$date1 <- as.Date(power1$date1, format="%d/%m/%Y")
power2 <- subset(power1, subset=(date1 >= "2007-02-01" & date1 <= "2007-02-02"))
datetime1 <- paste(as.Date(power2$date1), power2$time1)
power2$Datetime <- as.POSIXct(datetime1)
plot(power2$Global_active_power~power2$Datetime, type="l", ylab="Global Active Power (kilowatts)", xlab="")
当我运行上面的内容时,即使我运行摘要,head和str()我也看不到任何东西,我得到的图形就像我应该在x轴上的星期几在关于星期几的数据中。
我尝试用mutate添加我自己的日期列,但它没有用。
当我按照以下方式对其进行子集时,它无法正常工作。它在我只有我需要的数据的地方正确分组,但它不会用date1列或我通过mutate创建的星期几列绘制
power2 <- subset(power1, subset=(as.Date(date1, format = "%d/%m/%Y") >= "2007-02-01"
& as.Date(date1, format = "%d/%m/%Y") <= "2007-02-02"))
我知道as.Posixct会包含所有元数据,但是我不明白为什么当我将日期和时间列合并到它自己的列中时它才会在白天绘制在没有我询问的情况下,graph这一周。
当我像这样运行时,合并的日期和时间列数据被错误的年份损坏
power11 <- read.csv(file = "c:/datasets/household_power_consumption.txt", stringsAsFactors=F, header = TRUE,
sep=";", dec = ".", col.names = c("date1","time1","Global_active_power", "Global_reactive_power",
"Voltage","Global_intensity","Sub_metering_1","Sub_metering_2",
"Sub_metering_3"))
#colClasses = c("Date", "character", "factor", "numeric","numeric","numeric","numeric","numeric","numeric"))
power22 <- subset(power11, subset=(as.Date(date1, format = "%d/%m/%Y") >= "2007-02-01"
& as.Date(date1, format = "%d/%m/%Y") <= "2007-02-02"))
datetime1 <- paste(as.Date(power22$date1), power22$time1)
power22$Datetime <- as.POSIXct(datetime1)
答案 0 :(得分:0)
也许这个链接会有所帮助: http://earlh.com/blog/2009/07/07/plotting-with-custom-x-axis-labels-in-r-part-5-in-a-series/
为plot()调用添加一个参数:xaxt ='n'
plot(power2$Global_active_power~power2$Datetime, type="l", ylab="Global Active Power (kilowatts)", xlab="", xaxt='n')
告诉剧情不要添加x轴标签。然后添加一个axis()调用:
axis(side=1, at=power22$Datetime, labels=format(power22$Datetime, '%b-%y'))
我在这里使用'%b-%y',因为这是我在我引用的网站上看到的内容,但您可能希望使用适合您需要的格式代码。