Ben S.
Ben S.

Reputation: 3545

Simplify ggplot bar chart and make bars the same width

Here is my toy example:

yvalue = c(.1, .2, .3, .2, .1, .2, .3, .1)
df = data.frame(yvalue)
df$name = c("a", "b", "c", "d", "e", "f", "g", "h")
df$type = c("apple", "apple", "apple", "apple", "apple", "banana", "banana", "banana")
ggplot(data = df) + geom_bar(aes(y = yvalue, x=type, fill=name), stat = "identity", position = position_dodge())

Here is the resulting chart: enter image description here

This arrangement is basically what I want, but I'd like to do three things here that I have no clue how to do:

  1. make all the bars the same color
  2. remove the legend
  3. make all the bars the same width

Thanks!

Upvotes: 2

Views: 1805

Answers (2)

timfaber
timfaber

Reputation: 2070

Something like this?:

yvalue = c(.1, .2, .3, .2, .1, .2, .3, .1)
df = data.frame(yvalue)
df$name = c("a", "b", "c", "d", "e", "f", "g", "h")
df$type = c("apple", "apple", "apple", "apple", "apple", "banana", "banana", "banana")

fulldat <- rbind(df, cbind(yvalue=NA,expand.grid(name=df$name,type=df$type)))

ggplot(data = fulldat) + geom_bar(aes(y = yvalue, x=type, fill=name),width=0.5,stat = "identity",position=position_dodge(0.9)) +
  guides(fill=FALSE) + scale_fill_manual(values = rep("red",8))

Upvotes: 2

KoenV
KoenV

Reputation: 4283

when removing fill from the definition, you get rid both from the colours and the legend.

You could use the following code: I used facets to keep "type" in the picture.

ggplot(data = df) + 
geom_bar(aes(y = yvalue, x=name), stat = "identity", position = position_dodge()) +
facet_wrap(~type) +
theme_classic()

Please let me know whether this is what you want.

Upvotes: 1

Related Questions