我有一个存储在变量x中的以下格式“%d%m%Y”的数据集。 我想用直方图绘制频率(每月)。
日期从5月1日到10月31日。
我使用了以下代码:
hist(x,"months")
出现以下图表
您可以看到轴不是最佳的。它给人的印象是4月的数据是绘制的,而实际上是5月的数据。
有人可以帮我将标签放在条形图的中间 - 这意味着第一个元素是May,它会位于条形图的中间吗?
这是一个例子
set.seed(1)
x <- sample(seq(as.Date("2015-05-01"), as.Date("2015-10-31"), by="day"), 500, TRUE)
summary(x)
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# "2015-05-01" "2015-06-17" "2015-07-27" "2015-07-30" "2015-09-12" "2015-10-31"
hist(x, "months")
4月再次出现在情节中。
答案 0 :(得分:1)
感谢您的回答。
这就是我在平均时间内处理它的方式(代码不是最佳的(干净),因为它是为了显示变通步骤而不是最终代码而写的):
#Extract month from date format
x2 <- (format(x,"%m"))
#store it as a factor
x3 <- as.factor(x2)
#Replace factor names
levels(x3) <- c("May","June","July","August","September","October")
barplot(table(x3))
结果看起来像这样。
请注意,这不是密度图(histogram freq = F),而是一个条形图。
凝聚它看起来像我想象的那样(仅供参考 - 我是一个自学成才的编码员&#34;因此可以更好地创建清洁代码的方式/欢迎:
z <- as.factor((format(x,"%m")))
#Replacing factor names
levels(z) <- c("May","June","July","August","September","October")
#Plotting result
barplot(table(z))
由于您的有用提示,我设法让这项工作得以实现。 但是,我很惊讶使用正确的标签设置创建密度图非常困难。肯定会有一种更简单的方法吗?
亲切的问候,
答案 1 :(得分:0)
不确定为什么它不起作用......这是我的黑客工作。
a <- hist(x, "months") # store the histogram data
month <- strftime(x, "%m") # extract the month
dens <- (table(month)/sum(table(month)))/diff(a$breaks[-1]) # calculate the density
xax <- sort(c(as.numeric(unique(month)), max(as.numeric(unique(month))) + 1))
plot(xax, rep(max(dens), length(xax)), type = 'n', xaxt = 'n', yaxt = 'n', ylim = c(0, max(dens) + .002)) # blank plot
rect(xleft = xax[-length(xax)], ybottom = 0, xright = xax[-1], ytop = dens) # draw bins
axis(1, at = xax, labels = months(seq(as.Date("2015-05-01"), as.Date("2015-11-30"), by="month"))) # add x axis
axis(2, at = seq(0, max(dens), length = 4), labels = format(seq(0, max(dens), length = 4), digits = 2)) # add y axis