简体   繁体   English

如何使用R中的x,y数据绘制条形图和误差条

[英]How to plot bar plot and error bar with x,y data in R

I have data in following format.我有以下格式的数据。

X        ID         Mean       Mean+Error Mean-Error
61322107 cg09959428 0.39158198 0.39733463 0.38582934
61322255 cg17147820 0.30742542 0.31572314 0.29912770
61322742 cg08922201 0.47443355 0.47973039 0.46913671
61322922 cg08360511 0.06614797 0.06750279 0.06479315
61323029 cg00998427 0.05625839 0.05779519 0.05472160
61323113 cg15492820 0.10606674 0.10830587 0.10382761
61323284 cg02950427 0.36187007 0.36727818 0.35646196
61323413 cg01996653 0.35582920 0.36276991 0.34888849
61323667 cg14161454 0.77930230 0.78821970 0.77038491
61324205 cg25149253 0.93585347 0.93948514 0.93222180

How can i plot error bar plot with column(bars) enter image description here我如何绘制带有列(条)的误差条图,请在此处输入图像描述

where X-Axis is having X value.其中 X 轴具有 X 值。 So each bar will be plotted at X of fixed width.因此,每个条形都将绘制在固定宽度的 X 处。

I'll try answering.我会试着回答。 I am using a package called plotly .我正在使用一个名为plotly的包。 You can look here for more details.您可以在此处查看更多详细信息。

df <- read.csv('test.csv')
colnames(df) <- c("x", "id", "mean", "mean+error", "mean-error")
df$`mean+error` = df$`mean+error` - df$mean
df$`mean-error` = df$mean - df$`mean-error`

library(plotly)

p <- ggplot(df, aes(factor(x), y = mean)) + geom_bar(stat = "identity")
p <- plotly_build(p)

length(p$data)

p$layout$xaxis

plot_ly(df, x = 1:10, y = mean, type = "bar",  
        error_y = list(symmetric = F, 
                       array = df$`mean+error`,
                       arrayminus = df$`mean-error`,
                       type = "data")) %>% 
  layout(xaxis = list(tickmode = "array",tickvals = 1:10,ticktext = df$x))

I get this:我明白了:

在此处输入图片说明

The most popular approach would probably be using geom_errorbar() in ggplot2 .最流行的方法可能是在ggplot2使用geom_errorbar()

library("ggplot2")
ggplot(df, aes(x=ID, y = Mean)) + 
  geom_bar(stat="identity", fill="light blue") +
  geom_errorbar(aes(ymin = Mean.Error, ymax = Mean.Error.1))

where Mean.Error and Mean.Error.1 are the header names for mean +/- error you get when you try to read in your example as text.其中Mean.ErrorMean.Error.1是当您尝试将示例作为文本阅读时得到的均值 +/- 错误的标题名称。

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

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