【问题标题】:Dual y axis (second axis) use in ggplot2双 y 轴(第二轴)在 ggplot2 中使用
【发布时间】:2017-10-10 17:36:02
【问题描述】:

我遇到了一个问题,即在上一篇文章how-to-use-facets-with-a-dual-y-axis-ggplot 中描述的第二个轴函数的帮助下使用两个不同的数据。

我正在尝试使用 geom_pointgeom_bar,但由于 geom_bar 数据范围不同,因此在图表上看不到。

这是我尝试过的;

point_data=data.frame(gr=seq(1,10),point_y=rnorm(10,0.25,0.1))
bar_data=data.frame(gr=seq(1,10),bar_y=rnorm(10,5,1))

library(ggplot2)



sec_axis_plot <- ggplot(point_data, aes(y=point_y, x=gr,col="red")) +  #Enc vs Wafer
geom_point(size=5.5,alpha=1,stat='identity')+
geom_bar(data=bar_data,aes(x = gr, y = bar_y, fill = gr),stat = "identity") +
scale_y_continuous(sec.axis = sec_axis(trans=~ .*15,
                                         name = 'bar_y',breaks=seq(0,10,0.5)),breaks=seq(0.10,0.5,0.05),limits = c(0.1,0.5),expand=c(0,0))+

facet_wrap(~gr, strip.position = 'bottom',nrow=1)+
theme_bw()

可以看出 bar_data 已被删除。在这种情况下是否可以将它们绘制在一起??

谢谢

【问题讨论】:

  • 要使这一切正常工作,您需要将geom_bar 中的条形值除以 15,并使您的 limits 下降到 0 而不是从 0.1 开始(因为条形图从 0 开始)。

标签: r ggplot2


【解决方案1】:

您在这里遇到了问题,因为第二个轴的转换仅用于创建第二个轴 - 它对数据没有影响。您的 bar_data 仍在原始轴上绘制,由于您的限制,它仅上升到 0.5。这样可以防止出现条形。

为了使数据显示在同一范围内,您必须对条形数据进行规范化,使其与点数据处于同一范围内。然后,轴变换必须撤消这种标准化,以便您获得适当的刻度标签。像这样:

# Normalizer to bring bar data into point data range. This makes
# highest bar equal to highest point. You can use a different
# normalization if you want (e.g., this could be the constant 15
# like you had in your example, though that's fragile if the data
# changes).
normalizer <- max(bar_data$bar_y) / max(point_data$point_y)


sec_axis_plot <- ggplot(point_data,
                        aes(y=point_y, x=gr)) +

  # Plot the bars first so they're on the bottom. Use geom_col,
  # which creates bars with specified height as y.
  geom_col(data=bar_data,
           aes(x = gr,
               y = bar_y / normalizer)) + # NORMALIZE Y !!!

  # stat="identity" and alpha=1 are defaults for geom_point
  geom_point(size=5.5) +

  # Create second axis. Notice that the transformation undoes
  # the normalization we did for bar_y in geom_col.
  scale_y_continuous(sec.axis = sec_axis(trans= ~.*normalizer,
                                         name = 'bar_y')) +
  theme_bw()

这为您提供了以下情节:

我删除了您的一些花里胡哨,以使特定于轴的内容更加清晰,但是您应该可以毫无问题地将其添加回来。不过有几点注意事项:

  • 请记住,第二个轴是由主轴的 1-1 变换创建的,因此请确保它们在变换下覆盖相同的限制。如果您有应该归零的条形,则主轴应包括未转换的零模拟。

  • 确保数据归一化和轴转换相互撤消,以使您的轴与您正在绘制的值对齐。

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 2020-04-05
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多