简体   繁体   中英

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. So each bar will be plotted at X of fixed width.

I'll try answering. I am using a package called 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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