Home > other >  Using R/RStudio, how can I display both actual and target sales in a ggplot graph?
Using R/RStudio, how can I display both actual and target sales in a ggplot graph?

Time:05-16

I'm trying to generate a graph similar to the one in the image

Revenue by month

However, I havn't figured out how to display both the actual sales and the target sales, without creating a bar for the target (notice how in the image, the target is just a mark). The dataset I'm using is as follows:

Dataset

Where columns "text", "KGSFACT" and "porcentaje_VN" are not important. And instead of using months, I'm using the "SOLICITANTE" dimension. Also, I'm measuring sales with column "VALORNETO". Column "type" is to set the difference between actual and target sales.

The idea I have is something like use a filter inside the ggplot code chunk, but it doesn't seem right, and is actually not functional.

  ggplot(data = a7)  
  geom_bar(aes(x = SOLICITANTE, 
               type = "actual", 
               stat = "identity", 
               position = "dodge", 
               fill = type ) )  
  geom_point( aes( x = SOLICITANTE, 
                   y = VALORNETO,
                   type = "target") )   
  coord_flip()

Any idea how can I recreate a graph like the one in the image with ggplot?

CodePudding user response:

This should get you the bullet type structure, basically use geom_linerange() to create the target bars. For each factor the center coordinate of the bar is an integer 1,2,3...etc, so just calculate an appropriate length /- from the numeric value of the factors.

  ChartData <- data.frame(
  Category=factor(c("One", "Two", "Three")),
  Sales=c(100, 200, 300),
  Target=c(50, 250, 350),
  Exceed=c(T, F, F))

ggplot(data = ChartData, aes(x=Category, y=Sales))  
  geom_bar(stat="identity", aes(fill = Exceed))   coord_flip()   
  geom_linerange(
aes( xmin = as.numeric(Category)-0.4, 
xmax =  as.numeric(Category) 0.4, y = Target), size=1.25)   
geom_vline(aes(xintercept = as.numeric(Category) 0.5), color="grey")  
geom_vline(aes(xintercept = as.numeric(Category)-0.5), color="grey")   
theme_minimal()   
theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank())   xlab("")   
ylab("")

ggplot Barchart with Targets

CodePudding user response:

After some review, along with some help, I came up with an answer.

ggplot()  
  geom_col(data = a7 |> filter(type == "actual"), aes(x = reorder(SOLICITANTE, VALORNETO), 
                                                     y = VALORNETO, 
                                                     position="dodge", 
                                                     fill = SOLICITANTE ) )  
  geom_point(data = a7 |> filter(type == "target"), aes( x = SOLICITANTE, 
                                                        y = VALORNETO) )  
  coord_flip()

This way, we can now see both the actual sales and the target, both from the same dataset.

solution

  • Related