Robin
Robin

Reputation: 459

How to correct the number of bar label in ggplot2

This is the data:

doctor <- c("Dave", "Dave", "Sam", "Dave", "Dave", "Dave", "Dave", "Dave", "Sam", 
            "Peter", "Dave")
screened <- c(1,1,1,1,1,1,1,1,1,0,0)
df <- data.frame(doctor,screened)
df

And I tried to create the barplot like this:

ggplot(data=df, aes(x=doctor, fill=factor(screened))) +
  geom_bar(width=0.4) +
  geom_text(stat='count',aes(label=..count..), vjust=-0.3) + 
  xlab("Doctor") +
  ylab("Screening Times")

The plot showed like this:

enter image description here

How to flip the number of 7 and 1 in the first bar? Thanks!

Upvotes: 0

Views: 72

Answers (2)

KacZdr
KacZdr

Reputation: 1517

Alternatively, You can make such a plot that I think represents the data better:

ggplot(data=df, aes(x=doctor, fill=factor(screened))) +
  geom_bar(position = "dodge") +
  geom_text(position = position_dodge(0.9),stat='count',aes(label=..count..), vjust=-0.3, size=5) + 
  xlab("Doctor") +
  ylab("Screening Times")

enter image description here

Upvotes: 0

Edo
Edo

Reputation: 7858

Just add position = position_stack() in geom_text:

ggplot(data=df, aes(x=doctor, fill=factor(screened))) +
  geom_bar(width=0.4) +
  geom_text(stat='count',aes(label=..count..), vjust=-0.3, position = position_stack()) + 
  xlab("Doctor") +
  ylab("Screening Times")

enter image description here

Upvotes: 1

Related Questions