0

Minimal reproducible example is here:

library(ggplot2)

vals <- c(10, 12, 13, 20, 21, 28)
err <- c(0.85, 1.2, 0.9, 1.35, 2.2, 0.98)
cat <- c(rep("A",3),rep("B",3))

df <- data.frame(vals, err, cat)
df$cat<- as.factor(df$cat)

ggplot(df, aes(x=cat, y=vals, fill=vals)) +
  geom_bar(stat='identity', position='dodge') +
  geom_errorbar(aes(ymin=vals-err, ymax=vals+err), width=.1)

This code returns a plot like this: what is

however I expected two columns next to each other per cat. Closer to this:

should be

What am I doing wrong here?

1
  • I believe the continuous fill is confusing "dodge". One option is to switch to using "dodge2". Alternatively add group = factor(vals) into your global aes() so dodge knows the categories to dodge on. I think the latter might be easiest if you are going to added the dodged bars Commented Apr 27, 2021 at 14:42

1 Answer 1

1

If each row is a separate observation, you need to make that explicit. Make an index variable, turn it into a factor, and put that on the x-axis.

If obs is repeated across categories (e.g. if both A and B have obs numbered 1, 2 and 3), then facet on cat with facet_wrap(~ cat).


vals <- c(10, 12, 13, 20, 21, 28)
err <- c(0.85, 1.2, 0.9, 1.35, 2.2, 0.98)
cat <- c(rep("A",3),rep("B",3))

df <- data.frame(vals, err, cat)
df$cat<- as.factor(df$cat)
df$obs <- factor(1:nrow(df))

ggplot(df, aes(x=obs, y=vals, fill=cat)) +
  geom_col(position='dodge') +
  geom_errorbar(aes(ymin=vals-err, ymax=vals+err))

enter result

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.