[英]How to plot multiple lines with horizontal error bars from a dataframes using ggplot2 [in R]?
I am using this : 我用这个:
http://www.cookbook-r.com/Graphs/Plotting_means_and_error_bars_(ggplot2)/ http://www.cookbook-r.com/Graphs/Plotting_means_and_error_bars_(ggplot2)/
tutorial to plot multiple line graphs by grouping the data from a data frame. 通过对数据框中的数据进行分组来绘制多个折线图的教程。 Data looks like this:
数据如下所示:
> all
y x err lab
1 -41.93 5.7696373 0.9120865 he
2 -41.68 5.6345447 0.9100468 he
3 -41.43 5.4954702 0.9068282 he
4 -41.18 5.3588358 0.9054044 he
...
471 15.72 4.3701857 0.5170079 te
472 15.97 4.5128508 0.5262806 te
473 16.22 4.6592179 0.5320847 te
474 16.47 4.8052565 0.5397946 te
475 16.72 4.9518592 0.5465613 te
476 16.97 5.1057900 0.5504546 te
477 17.22 5.2503157 0.5602737 te
478 17.47 5.4000783 0.5711784 te
479 17.72 5.5506885 0.5830945 te
480 17.97 5.7085180 0.6109026 te
And i am using following line to plot the graph: 我正在使用以下行来绘制图表:
ggplot(all, aes(x,y, colour=lab, group=lab)) + geom_errorbarh(aes(xmin=x-err, xmax=x+err)) + geom_line() + geom_point()
What I got is as follows: 我得到的是如下:
I just want to fix remove the vertical lines. 我只想修复删除垂直线。 They should look lien two separate lines (each colour) and with their own horizontal error bars.
它们应该看起来有两条独立的线(每种颜色)和它们自己的水平误差条。
What should I correct in ggplot function? 我应该在ggplot函数中纠正什么? Thanks a lot!
非常感谢!
Data 数据
all <- structure(list(y = c(-41.93, -41.68, -41.43, -41.18, 15.72, 15.97,
16.22, 16.47, 16.72, 16.97, 17.22, 17.47, 17.72, 17.97), x = c(5.7696373,
5.6345447, 5.4954702, 5.3588358, 4.3701857, 4.5128508, 4.6592179,
4.8052565, 4.9518592, 5.10579, 5.2503157, 5.4000783, 5.5506885,
5.708518), err = c(0.9120865, 0.9100468, 0.9068282, 0.9054044,
0.5170079, 0.5262806, 0.5320847, 0.5397946, 0.5465613, 0.5504546,
0.5602737, 0.5711784, 0.5830945, 0.6109026), lab = structure(c(1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("he",
"te"), class = "factor")), .Names = c("y", "x", "err", "lab"), class = "data.frame", row.names = c("1",
"2", "3", "4", "471", "472", "473", "474", "475", "476", "477",
"478", "479", "480"))
The problem is with the use of geom_line()
for a dataset where the same x in each group may map to multiple y values. 问题在于对数据集使用
geom_line()
,其中每个组中的相同x可以映射到多个y值。 geom_line
tries to connect data points continuously from lowest to highest x which is why you get the (almost) vertical lines in your graph. geom_line
尝试连续从最低x到最高x连接数据点,这就是你在图中得到(几乎)垂直线的原因。 Use geom_path
instead. 请改用
geom_path
。 For an example, compare 举个例子,比较一下
df <- data.frame(
y = -5:5,
x = (-5:5)^2
)
# geom_line
ggplot(df) +
aes(x, y) +
geom_line()
# geom_path
ggplot(df) +
aes(x, y) +
geom_path()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.