2017-10-10 355 views
1

我遇到了一个问题,即如前一篇文章how-to-use-facets-with-a-dual-y-axis-ggplot中所述,在借助第二轴功能的情况下使用两个不同的数据。ggplot2中使用双y轴(第二轴)

我正在尝试使用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

+0

为了完成这一切工作,您需要在'geom_bar'中将您的bar值除以15,并使您的'limits'降至0而不是从.1开始(因为bar从0开始)。 – aosmith

回答

2

你遇到了问题在这里,因为第二轴的改造仅用于创建第二个轴 - 其对数据没有影响。您的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变换创建的,因此请确保它们在变换下覆盖相同的极限。如果你有条应该归零,那么主轴应该包含零变换的模拟。

  • 确保数据标准化和轴变换相互撤销,以便轴与您绘制的值保持一致。