0
votes

I am using ggplot2 geom_bar to make a series of bar charts. Each city has three data points, and I am making a graph for each city. I want to label the second and third bar in each chart as a percent of the previous bar (e.g. data that looks like 5, 4, 3 would read 5, 80%, 75%).

In this data, I am value should be the label for bar 1 in all graphs. dum2/dum1*100 should be the label for the bar with the value of dum2. dum3/dum2*100 should be the label for the bar with value dum3.

Example

State <- c("AA","AB","AC","AD","AE")
dum1 <- c(34, 30, 8, 22, 5)
dum2 <- c(22.5, 28.1, 3, 12, 1)
dum3 <- c(12.8, 23, 2.8, 11.9, 0.3)
df <- data.frame(State, dum1, dum2, dum3)
m1 <-melt(df)

for(i in levels(m1$State)) 
p <- ggplot(subset(m1, State==i), aes(variable, value,  fill = variable)) +
facet_wrap(~ State) + 
geom_bar(stat="identity", show_guide=FALSE) + 
geom_text(aes(x=variable, y=value + 2, label=round(value,digits=0)), vjust=0,
        size=30) +
theme(axis.title.x = element_blank(),
    plot.background = element_rect(fill = "transparent", color=NA),
    panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
    panel.border = element_blank(), panel.background = element_blank(),
    axis.line = element_blank(), axis.title.y=element_blank(),
    axis.line = element_blank(), 
    axis.text.x = element_blank(), 
    axis.text.y = element_blank(),
    axis.ticks = element_blank(), 
    axis.title.y = element_blank(),
    strip.text.x = element_blank(),
    strip.background = element_rect(fill="transparent")
     ) +
     scale_y_continuous(limits=c(0,40)) +
    scale_fill_manual(values=c("navy", "coral", "gold")) +
  ggsave(sprintf("plot %s.jpg", i))

I have tried adding in a column with the calculated percent for the relevant rows, but don't know how to call a column for only selected data points on the graph. I used something like

lab<-c(0,0,0,0,0,66.2,93.7,37.5,54.5,20.0,56.9,81.9,93.3,99.2,30.0)

but cannot figure out how to call it appropriately for the correct bars.

1
why not just replace the 0s with the numbers that the first bars should be labeled with? eg lab <- round ( c (dum1, dum2/dum1*100, dum3/dum2*100), 1)janattack

1 Answers

1
votes

Without all the extraneous formatting, this seems to do what you are asking:

ggplot(subset(m1, State=="AA"), aes(variable, value,  fill = variable)) +
  facet_wrap(~ State) + 
  geom_bar(stat="identity", show_guide=FALSE) + 
  geom_text(aes(x=variable, y=value + 2, 
                label=paste0(round(value/c(1,0.01*head(value,-1))),c("","%","%"))))