双y轴(第二轴)用于ggplot2

时间:2017-10-10 17:36:03

标签: r ggplot2

我遇到了一个问题,即在第二轴功能的帮助下使用两个不同的数据,如上一篇文章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已被删除。可以在这种情况下将它们一起绘制吗?

THX

enter image description here

1 个答案:

答案 0 :(得分:6)

这里遇到问题,因为第二轴的转换仅用于创建第二轴 - 它对数据没有影响。您的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()

这会给你以下情节:

enter image description here

我删除了一些你的铃声和口哨,使轴特定的东西更清晰,但你应该能够毫无问题地添加它。但有几点注意事项:

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

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

相关问题