如何强制x轴刻度标记出现在热图图形的栏末尾?

时间:2012-05-22 21:29:17

标签: r ggplot2

我用 ggplot2 创建了一个简单的热图图形但我需要强制x轴刻度标记出现在我的x变量的末尾,而不是它的中心。例如,我希望1出现在1.5现在的位置。我相信在Base R中完成的热图可以做到这一点。

library(car) #initialize libraries
library(ggplot2)  #initialize libraries
library(reshape)

df=read.table(text= "x  y  fill
1 1 B
2 1 A
3 1 B
1 2 A
2 2 C
3 2 A
",  header=TRUE, sep=""  )

#plot data
qplot(x=x, y=y, 
      fill=fill, 
      data=df, 
      geom="tile")+  
      scale_x_continuous(breaks=seq(1:3) ) 

enter image description here

想法是创建一个简单的热图,如下所示: enter image description here

此图表中的刻度线位于条形的末尾,而不是它们的中心

2 个答案:

答案 0 :(得分:4)

这个怎么样?

object = qplot(x=x, y=y, 
      fill=fill, 
      data=df, 
      geom="tile")+  
      scale_x_continuous(breaks=seq(1:3))

object + scale_x_continuous(breaks=seq(.5,3.5,1), labels=0:3)

enter image description here

答案 1 :(得分:3)

geom_tile将每个图块放在给定坐标处。因此,您会期望它所提供的输出。

因此,如果给ggplot每个单元格的中心(不是右上角坐标),它将起作用。

ggplot(df, aes(x = x-0.5, y = y-0.5, fill = fill)) + 
  geom_tile() + 
  scale_x_continuous(expand = c(0,0), breaks = 0:3) + 
  scale_y_continuous(expand = c(0,0), breaks = 0:3) + 
  ylab('y') + 
  xlab('x')

或使用qplot

qplot(data = df, x= x-0.5, y = y-0.5, fill = fill, geom = 'tile')  + 
   scale_x_continuous(expand = c(0,0), breaks = 0:3) + 
   scale_y_continuous(expand = c(0,0), breaks = 0:3) + 
   ylab('y') + 
   xlab('x')