Ggplot2 - bar on the bar - plan implementation graph

Hello.
I would like to make a sales fulfillment chart, a stroke bar plan (Plan), a fill bar implementation (Realizacja).
Unfortunately, I don't know how to go about it, I tried geom_bar but without a specific offense.

I would like it to look more or less like a chart in exel:

My data:

df <- data.frame( Miesiac = c('styczeń', 'luty', 'marzec', 'kwiecień', 'maj', 'czerwiec', 'lipiec', 'sierpień', 'wrzesień', 'październik', 'listopad', 'grudzień')
                , Plan = c(2000000, 2000000, 2000000, 2000000, 2000000, 2200000, 2500000, 2500000, 2500000, 2500000, 2500000, 3000000)
                , Realizacja = c(1000000, 1200000, 1262076, 2000000, 2500000, 3500000))

Can you help me make such a chart.

Hi!

In ggplot2 you can plot different layers on top of each other. In your case you can at first plot the Plan bars and then the implementation bars on top. Here is an example:

suppressPackageStartupMessages({
  library(dplyr)
  library(ggplot2)})

mydf <- data.frame( Miesiac = c('styczeń', 'luty', 'marzec', 'kwiecień', 'maj', 'czerwiec', 'lipiec', 'sierpień', 'wrzesień', 'październik', 'listopad', 'grudzień')
                  , Plan = c(2000000, 2000000, 2000000, 2000000, 2000000, 2200000, 2500000, 2500000, 2500000, 2500000, 2500000, 3000000)
                  , Realizacja = c(1000000, 1200000, 1262076, 2000000, 2500000, 3500000,0,0,0,0,0,0))
# Add percentage column for labels
mydf<-mydf%>%mutate(percent=Realizacja/Plan*100)


# convert months? column into factor to preserv order 
mydf$Miesiac<-factor(mydf$Miesiac,levels=mydf$Miesiac)

# plot
mydf%>%ggplot(aes(x=Miesiac))+
  geom_bar(aes(y=Realizacja),stat = "identity",fill="lightblue")+
  geom_bar(aes(y=Plan),stat = "identity",alpha=0,colour="black")+
  geom_label(aes(y=Realizacja, label=paste0(round(percent,0),"%")))+
  scale_y_continuous(labels = scales::comma)

Created on 2021-01-18 by the reprex package (v0.3.0)

Note that I filled in the Realizacja column with zeros, otherwise it would have been recycled.

Does this help you?

2 Likes

Very nice and simple thank you.

I still have a problem with displaying this graph in ggplotly(), label does not display.

GGplotly doesn't support geom_label, but you can use geom_text() instead.

It works, thank you so much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.