【问题标题】:Align the primary and secondary y-axis on the common base, set points in the center of bars?在公共底座上对齐主要和次要 y 轴,在条形中心设置点?
【发布时间】:2017-03-14 10:45:54
【问题描述】:

我正在尝试在辅助 y 轴上显示用线图覆盖的条形图。我在这里遵循示例:http://robjhyndman.com/hyndsight/r-graph-with-two-y-axes/。我成功显示了我的数据,但是 y1 和 y2 轴的开头不是从公共基础(在公共 0 上)开始,y2 位于更上方。

如何在公共基础上正确对齐y1和y2轴?我可以将我的 y1 和 y2 轴都扩展为相同的尺寸吗?还有,如何调整条形中间点的位置?

我的虚拟数据:

x <- 1:5
y1 <- c(10,53,430,80,214)
y2 <- c(0.2,1.2,3.3, 3.5, 4.2)

# create new window 
windows()

# set margins
par(mar=c(5,4,4,5)+.1)
# create bar plot with primary axis (y1)
barplot(y1,  ylim= c(0,500))
mtext("y1",side=2,line=3)

# add plot with secondary (y2) axis
par(new=TRUE)
plot(x, y2,,type="b",col="red",xaxt="n",yaxt="n",xlab="",ylab="", ylim= c(0,10), lwd = 2, lty = 2, pch = 18)
axis(4)
mtext("y2",side=4,line=3)

【问题讨论】:

  • 只需将yaxs = 'i' 添加到第二个绘图命令即可。
  • 酷,谢谢!!你能把这个作为答案发布,我可以接受吗?
  • 拜托,你还有什么建议可以把我的“点”放在我的酒吧中间吗?我试图在 par() 中玩 xaxs,但我无法弄清楚....
  • 在我的回答中添加了一些相关信息

标签: r plot yaxis


【解决方案1】:

查看par() 的文档时,您会发现xaxsyaxs 选项,您可以使用它们控制两个轴的间隔计算。在您的 plot() 命令之前调用 par(yaxs = 'i') 或将选项直接用作 plot() 的参数将通过以下方式更改间隔计算:

样式“i”(内部)只是找到一个带有漂亮标签的轴 在原始数据范围内。

TO 关于他的评论的其他信息:

为了使线的点居中,请改用lines,您可以使用 barplot 创建的 x 轴:

par(mar=c(5,4,4,5)+.1)
# create bar plot with primary axis (y1)
par(xpd = F)
ps <- barplot(y1,  ylim= c(0,500), xpd = F)
axis(4, at = 0:5 * 100, labels = 0:5 * 2)  # transform values
mtext('y1',side = 2, line = 3)
lines(x = ps, y = y2 * 50, type = 'b', col = 'red') # transform values

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多