如何绘制连续x轴的条形图/条形图

时间:2014-03-20 08:53:12

标签: r ggplot2 bar-chart

我想绘制一个barplot,但我在x轴上有日期,我希望这些日期间隔正确(因为它是非绝对的)

set.seed(1)
m = matrix(abs(rnorm(6)),3,2)
rownames(m) = as.Date(c('2011-01-01','2011-01-03','2011-01-10'))
barplot(t(m),beside=T,col=c('red','blue'),las=2)

enter image description here

在这个例子中,我希望14984在右边偏移。 我宁愿使用graphics解决方案,但ggplot2也很好

2 个答案:

答案 0 :(得分:7)

您是否介意使用'headerplot'?

library(ggplot2)
set.seed(1)
df <- data.frame(y=abs(rnorm(6)),
                 x=rep(as.Date(c('2011-01-01','2011-01-03','2011-01-10')),
                       times = 2),
                 g = factor(rep(c(1,2), each = 3)))    
ggplot(aes(x=x, y=y, group = g, fill = g), data = df) +
  geom_bar(stat = 'identity', position = 'dodge')

enter image description here

您可以使用`scale_x_date'

改善轴格式
library(scales)
ggplot(aes(x=x, y=y, group = g, fill = g), data = df) +
  geom_bar(stat = 'identity', position = 'dodge') +
  scale_x_date(breaks = '1 day') +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

scale_X_date

根据您的目的定制

ggplot(aes(x=x, y=y, group = g, fill = g), data = df) +
  geom_bar(stat = 'identity', position = 'dodge') +
  scale_x_date(breaks = '1 day') +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  scale_fill_manual('My\nclasses', values = c('1'='red', '2' = 'blue')) +
  labs(list(title = 'Barplot\n', x = ('Date'), y = 'Values'))

customized plot

答案 1 :(得分:1)

使用graphics,您可能需要相应地准备数据(缺少您不考虑的日期值)才能执行此操作。然后你可以使用barplot

# matrix definition
set.seed(1)
m = matrix(abs(rnorm(6)),3,2)
rownames(m) = as.Date(c('2011-01-01','2011-01-03','2011-01-10'))
# get all dates in between
dts <- do.call(":", as.list(range(rownames(m))))
dts <- dts[!dts%in%rownames(m)]
mat <- matrix(NA, nrow=length(dts), ncol=2, dimnames=list(dts, NULL))
# combine with original matrix
m <- rbind(m, mat)
m <- m[order(rownames(m)), ]
which(!is.na(m[,1]))
# plot
barplot(t(m), beside=T, col=c('red','blue'),las=2, axes=FALSE, axisnames=FALSE)
axis(2)
axis(1, at=3*which(!is.na(m[,1]))-1, labels=rownames(m[!is.na(m[,1]),]))