Mus
Mus

Reputation: 7550

How to add a second set of labels to second set of data points

I have added labels (2016 response rate) to the bars of my barchart but want to also add labels to the individual/black data points (2015 response rate) that lie inside each bar.

enter image description here

This is my code:

ggplot(merged2[merged2$TrustCode %in% acuteCodes, ], aes(x = TrustName, y = ResponseRate16)) + 
  geom_bar(fill="white",stat="identity", colour="blue") +
  geom_point(aes(x = TrustName, y = ResponseRate15), shape=18, size=3, colour="black") +
  geom_text(aes(label=ResponseRate16, x=TrustName, y=1.10*ResponseRate16), colour="black")

How can this be achieved?

Upvotes: 0

Views: 1773

Answers (1)

GGamba
GGamba

Reputation: 13680

Exactly like you mapped the bar values: add a geom_text()

ggplot(merged2[merged2$TrustCode %in% acuteCodes, ], aes(x = TrustName, y = ResponseRate16)) + 
  geom_bar(fill = "white", stat = "identity", colour = "blue") +
  geom_point(aes(y = ResponseRate15), shape = 18, size = 3, colour = "black") +
  geom_text(aes(label = ResponseRate16, y = 1.10*ResponseRate16), colour="black") +
  geom_text(aes(label = ResponseRate15, y = 1.10*ResponseRate15), colour="red")

I slightly cleaned up you code of repeated x mappings. No need to duplicate an aesthetic if it's already mapped in the initial ggplot function.

You probably also want to use the nudge_y arg instead of setting a new y aesthetic.

ggplot(merged2[merged2$TrustCode %in% acuteCodes, ], aes(x = TrustName, y = ResponseRate16)) + 
      geom_bar(fill = "white", stat = "identity", colour = "blue") +
      geom_text(aes(label = ResponseRate16), nudge_y = .5, colour="black") +
      geom_point(aes(y = ResponseRate15), shape = 18, size = 3, colour = "black") +
      geom_text(aes(label = ResponseRate15, y = ResponseRate15), nudge_y = .5, colour="red")

Upvotes: 2

Related Questions