【问题标题】:How to avoid wired ylab error when plotting in R在 R 中绘图时如何避免有线 ylab 错误
【发布时间】:2014-03-29 17:50:27
【问题描述】:

我需要一个两个 y 轴图形。 hrbrmstr 建议使用简单的绘图。但是在将图表调整到我的设置时,我观察到我无法在右侧添加 ylab,出现连线错误:

Error in axis(4, ylim = c(0, 1), col = "black", col.axis = "black", las = 1,  : 
'labels' is supplied and not 'at'

这是可以避免的吗? 看代码底线fprSOURCE OF ERROR

featPerf <- data.frame( expS=c("1", "2", "3", "4"),
                        exp1=c(1000, 0, 0, 0),
                        exp2=c(1000, 5000, 0, 0),
                        exp3=c(1000, 5000, 10000, 0),
                        exp4=c(1000, 5000, 10000,20000),
                        accuracy=c(0.4, 0.5, 0.65, 0.9) )

# make room for both axes ; adjust as necessary
par(mar=c(5, 5, 5, 7) + 0.2) 

# plot the bars first with no annotations and specify limits for y
#barplot(as.matrix(featPerf[,2:5]), axes=FALSE, xlab="", ylab="", ylim=c(0, max(colSums(featPerf[2:5]))))
barplot(as.matrix(featPerf[,2:5]), axes=FALSE, xlab="", ylab="", beside=TRUE)

# make the bounding box (or not...it might not make sense for your plot)
#box()

# now make the left axis
axis(2, ylim=c(0, max(colSums(featPerf[2:5]))), col="black", las=1)

# start a new plot
par(new=TRUE)

# plot the line; adjust lwd as necessary
plot(x=1:4, y=featPerf[,6], xlab="Experiments", ylab="Abs. # of Features", axes=FALSE, type="l", ylim=c(0,1), lwd=5)

# annotate the second axis -- SOURCE OF ERROR ->           VVVVVVVVVVVVVVVVVV
axis(4, ylim=c(0,1), col="black", col.axis="black", las=1, labels="Accuracy")

【问题讨论】:

  • labels 的参数axis 定义了在刻度线旁边打印的内容,而不是轴“名称”。您没有定义刻度的位置,这就是您收到此错误的原因。
  • @Roland 谢谢。我怎样才能避免这种情况?能否提供最后一行的代码axes(4, ylim=...
  • 我不确定你想在那里做什么。不要将值传递给labels?研究文档。
  • @Roland 我试图在这里理解问题:statmethods.net/advgraphs/axes.html(下到“Axes”)但是,他们说用labels=可以把ylab对应的命令,创建整个图时(这里不可能直接因为有两个 Y 轴)
  • 我看不出他们在哪里说过这样的话。事实上,他们展示了如何使用 mtext 向右轴添加标签。

标签: r plot axis-labels


【解决方案1】:

像这样?

par(mar=c(4,4,1,4) + 0.2) 
barplot(as.matrix(featPerf[,2:5]), axes=FALSE, xlab="", ylab="", beside=TRUE)
axis(2, ylim=c(0, max(colSums(featPerf[2:5]))), col="black", las=1)
par(new=TRUE)
plot(x=1:4, y=featPerf[,6], xlab="Experiments", ylab="Abs. # of Features", axes=FALSE, type="l", ylim=c(0,1), lwd=5, col="blue")
axis(4, ylim=c(0,1), col="blue", col.axis="blue", las=1)
mtext("Accuracy",4,line=2, col="blue") 

郑重声明,从不以这种方式(使用两个轴)将图堆叠在一起是一个好主意。我已经将线和轴设置为相同的颜色,以试图引起人们对您正在做的事情的注意,但是这仍然是一个非常糟糕的主意

【讨论】:

  • @johoward 非常感谢!我只需要这个堆积图。 :) 祝你有美好的一天。
【解决方案2】:

首先,不建议在同一个绘图中使用两个 Y 轴。

如果您将 at 参数添加到 axis 调用,您会在图的右侧获得名称“Accuracy”。

axis(4, ylim=c(0,1), col="black", col.axis="black", las=1, labels="Accuracy",
     at = .5)

【讨论】:

  • 谢谢。好的,但现在我没有规模。我需要这个带有两个 y 轴的图,名称为“Accuracy”,值从01。这在技术上是不可能的吗?
猜你喜欢
  • 2015-07-01
  • 2018-10-24
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-21
  • 2021-01-21
相关资源
最近更新 更多