【问题标题】:Twosided Barplot in R with different dataR中具有不同数据的双边条形图
【发布时间】:2017-04-29 14:24:38
【问题描述】:

我想知道是否有可能获得显示每个 X 值的 Data A 上方和 Data B 下方的双面条形图(例如 Two sided bar plot ordered by date)。

数据 A 可以是一个人的年龄,数据 B 是同一个人的大小。这个问题以及与上述示例的主要区别:A 和 B 显然具有完全不同的单位/ylims。

示例:

X = c("Anna","Manuel","Laura","Jeanne") # Name of the Person
A = c(12,18,22,10)     # Age in years
B = c(112,186,165,120) # Size in cm 

任何想法如何解决这个问题?我不介意水平或垂直解决方案。

非常感谢!

【问题讨论】:

    标签: r bar-chart


    【解决方案1】:

    这里的代码可以为您提供我认为您想要使用基础 R 中的 barplot 的可靠草稿。我只是将一个系列设为负数,然后手动设置 axis 中的标签以引用原始(正)值。您必须选择如何缩放这两个系列,这样比较仍然可以提供信息。我在这里通过将高度(以厘米为单位)除以 10 来做到这一点,这会产生与多年来的范围相似的范围。

    # plot the first series, but manually set the range of the y-axis to set up the
    # plotting of the other series. Set axes = FALSE so you can get the y-axis
    # with labels you want in a later step.
    barplot(A, ylim = c(-25, 25), axes = FALSE)
    
    # plot the second series, making whatever transformations you need as you go. Use
    # add = TRUE to add it to the first plot; use names.arg to get X as labels; and
    # repeat axes = FALSE so you don't get an axis here, either.
    barplot(-B/10, add = TRUE, names.arg = X, axes = FALSE)
    
    # add a line for the x-axis if you want one
    abline(h = 0)
    
    # now add a y-axis with labels that makes sense. I set lwd = 0 so you just
    # get the labels, no line.
    axis(2, lwd = 0, tick = FALSE, at = seq(-20,20,5),
         labels = c(rev(seq(0,200,50)), seq(5,20,5)), las = 2)
    
    # now add y-axis labels
    mtext("age (years)", 2, line = 3, at = 12.5)
    mtext("height (cm)", 2, line = 3, at = -12.5)
    

    par(mai = c(0.5, 1, 0.25, 0.25)) 的结果:

    【讨论】:

    • 太棒了,正是我想要的!谢谢! :-)
    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多