简体   繁体   English

如何在具有一个x轴和两个y轴的图中将误差线缩放到右y轴的尺寸

[英]How to scale the errorbars to the dimensions of the right y-axis in a plot with one x-axis and two y-axis

I have a dataframe df1 as below. 我有一个数据df1如下。

df1<-data.frame(Hour=c(0,3,6,9,12,15,18,21),
                n=c(18426,19345,20123,21450,23456,23510,21453,18456),
                mean=c(23.9234, 34.9456,28.9891,44.6452,47.4567,38.9483,34.9632,29.8765),
                ci=c(4.2345,6.3345,12.1345,17.3445,13.1545,12.1745,10.1945,28.2445))
df1$Hour<-as.factor(df1$Hour)
df1

  Hour     n    mean      ci
1    0 18426 23.9234  4.2345
2    3 19345 34.9456  6.3345
3    6 20123 28.9891 12.1345
4    9 21450 44.6452 17.3445
5   12 23456 47.4567 13.1545
6   15 23510 38.9483 12.1745
7   18 21453 34.9632 10.1945
8   21 18456 29.8765 28.2445

I created the plot that I show below after some search on the internet, with one x-axis and two y-axis. 在互联网上进行搜索后,我创建了下面显示的图表,其中有一个x轴和两个y轴。 The left y-axis showing the variable n and the right y-axis showing the variable mean . 左y轴显示变量n ,右y轴显示变量mean The "orange" line represents the confidence interval ( ci ) for the mean (right y-axis). “橙色”线表示平均值(右y轴)的置信区间( ci )。

ggplot() + 
  geom_bar(mapping = aes(x = df1$Hour, y = df1$n), stat = "identity", fill = "grey") +
  geom_line(mapping = aes(x = df1$Hour, y = df1$mean*494.2611, group=1 ), size = 1, color = "blue") + # 525.3868 result from the division of 23456/44.6452
  geom_point(mapping = aes(x = df1$Hour, y = df1$mean*494.2611 )) + 
  scale_y_continuous(name = "n", 
                     sec.axis = sec_axis(~./494.2611, name = "Mean")) + 
  theme(
    axis.title.y = element_text(color = "darkgrey"),
    axis.title.y.right = element_text(color = "blue")) + 
  labs(x = "Hour") +
  geom_errorbar(mapping= aes(x = df1$Hour, ymin = df1$mean*494.2611 - df1$ci, ymax = df1$mean*494.2611 + df1$ci),
                position = position_dodge(0.9),
                width = 0.4, colour = "orange", 
                alpha = 0.9, size = 0.5)

在此处输入图片说明

The problem is that the errorbars appear too small compare to the scale of the variable mean , and hence all look the same way. 问题在于,与可变mean的刻度相比,误差线显得太小了,因此它们看起来都是一样的。 I think that the errorbars are scaled to the left y-axis. 我认为误差线被缩放到左侧的y轴。

Does anyone know where is the mistake? 有人知道错误在哪里吗?

You forgot your parentheses. 你忘了括号。 Instead of 代替

 ymin = df1$mean*494.2611 - df1$ci

use 采用

 ymin = (df1$mean - df1$ci) * 494.2611

(same for ymax) (与ymax相同)

Explanation: dual scales in ggplot is a hack. 说明: ggplot中的双刻度是一个hack。 You have to manually rescale the data to fit the primary scale. 您必须手动重新缩放数据以适合主要比例。 For error bars, you need ymin and ymax, and these are the values that you need to scale. 对于误差线,您需要ymin和ymax,这些是您需要缩放的值。 But ymin=df1$mean - df1$ci , so you need to multiply the whole value, not just the mean. 但是ymin=df1$mean - df1$ci ,因此您需要乘以整个值,而不仅仅是均值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM