rrestggplot2bar-chartgriddb

Using R to plot a stacked bargraph but the legend does not show up , using GridDB as my database


I wrote an R function to read data from GridDB, and then plot a stacked bar graph. After reading the data from GridDB, I store it in a "tibble" ( not a full fledged data frame, a tibble is a simple data structure and can easily be fed to a POST Web API). When I plot a stacked bar graph, the bars are visible but the legend is not. I used many variations but the legend is still not visible, even after clearly specifying the args.legend parameter to the barplot() function. Stacked Bar graph image is attached. Dummy data is here in CSV format - https://docs.google.com/spreadsheets/d/1u73_f7VJms0dv1-Qk_ScswB6vUPPNWeSp3xpeLfASgU/edit?usp=sharing
Below is the relevant snippet from my code.

..... # Use GridDb's web API to return relevant data qr1 <- GET (url = my_query_url, add_headers("Content-Type" = "application/json; charset=UTF-8" ) ,
config = authenticate("my_user_name", "mypass"), body = query_request_body ) #Copy data returned into an R tibble
my_global_health__data <- qr1
# Plot the bars barplot( matrix(c(my_global_health__data$Percent, my_global_health__data$otherCol), nrow=2, ncol=20, byrow=TRUE), main="Cause of death, by communicable diseases

and maternal, prenatal and nutrition conditions", names.arg = my_global_health_data$CountryCode , xlab="CountryName", ylab="Percent of Total", col=c("blue","red"),

args.legend="bottomright" )

print("EOP, R and GridDB") 
#`

.................... `

Can you give me some idea about what I am doing incorrectly, OR just post a barplot() function that works for you and shows up the legend too.

Stacked Bar chart I get Thanks Pratik

Used R language's barplot function, but the legend is not visible. the parameter args.legend does not seem to work for me. barplot(H, xlab, ylab, main, names.arg, col, args.legend)


Solution

  • Since you didn't provide the data directly, I just created some dummy data. I used ggplot2 and did not have any issues, after shaping the data into long format.

    library(tidyverse)
    library(googlesheets4)
    
    set.seed(123)
    
    name <- c("A", "B", "C", "D")
    cause1 <- sample(55:98, 4)
    cause2 <- sample(55:98, 4)
    
    df <- tibble(name, cause1, cause2)
    
    df %>%
      pivot_longer(cols = 2:3, names_to = "cause", values_to = "perc") %>%
      ggplot(aes(x=name, y=perc, fill=cause))+
      geom_col()
    

    Created on 2023-04-17 with reprex v2.0.2