【问题标题】:Is it possible to break axis labels into 2 lines in base graphics?是否可以在基本图形中将轴标签分成两行?
【发布时间】:2010-11-26 14:05:56
【问题描述】:

我试图将 x 轴标签分成两行。我还希望将标签旋转 45 度。我该怎么做?

到目前为止我所拥有的:

N <- 10
dnow <- data.frame(x=1:N, y=runif(N), labels=paste("This is observation ",1:N))
with(dnow, plot(x,y, xaxt="n", xlab=""))
atn <- seq(1,N,3)
axis(1, at=atn, labels=labels[atn])

【问题讨论】:

  • 2 行是什么意思?你的意思是你想要“这是\n观察......”?
  • @chis_dubois 这是答案的第一部分!谢谢!

标签: graphics r


【解决方案1】:

这是ggplot2 包的一种可能性。

N <- 10
labs <- factor(1:N,labels=paste("This is \n observation",1:N))
dnow <- data.frame(x=1:N, y=runif(N), labels=labs)
qplot(labels,y,data=dnow) + 
      opts(axis.text.x=theme_text(angle=-45,hjust=0))

我也期待看到基本包示例!

【讨论】:

  • @chris - 我愿意接受你的问题(现在所有酷孩子都在使用 ggplot2)。但是,您能否事先修复 x 轴(ggplot 按字母顺序排列字符向量,因此您必须将其转换为因子。)谢谢!
  • 好建议。我将其切换为一个因素,但右侧仍然被切断。我会尝试解决这个问题。
  • 这也适用于数据标签 - 如果你将 \n 放入其中,它将断行!
【解决方案2】:

这是我使用基本图形制作的(在我的 ggplot2 天之前):

## data
N <- 10
dnow <- data.frame(x=1:N, y=runif(N), labels=paste("This is \nobservation ",1:N))
## make margins wide
par(mfrow=c(1,1), mar=c(10,10,6,4))
## plot without axix labels or ticks
with(dnow, plot(x,y, xaxt="n", xlab=""))
## the positions we ant to plot
atn <- seq(1,N,3)
## the label for these positions
lab <- dnow$labels[atn]
## plot the axis, but do not plot labels
axis(1, at=atn, labels=FALSE)
## plot labels
text(atn, ## x position
     par("usr")[3]-.05, ## position of the low axis
     srt=45, ## angle
     labels=lab, ##labels
     xpd=TRUE, ## allows plotting outside the region 
     pos=2)
## par("usr")[3]

【讨论】:

  • 我认为这也是一个重要的贡献。对于ggplot2,这可能不是必需的。但它也很好。 Paul Murrel 在 R Graphics 书中还提供了一个更好、更优雅的解决方案,grid
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
  • 2015-07-27
相关资源
最近更新 更多