rggplot2rcharts

Donut plot with echatr and ggplot2


I have the following data and I need to make a graph similar to the one I made in tableau

df<-data.frame(estado=c("Aprobado","Reprobado"),
               freq=c(551,7),
             porcentaje=c(0.99,1))

The graph with echatr looks like this

df %>% 
    head() %>% 
    mutate(estado = row.names(.)) %>% 
    e_charts(estado) %>% 
    e_pie(freq, radius = c("50%", "70%")) %>% 
    e_title("Donut chart")

enter image description here

I don't understand why I can't put the labels or titles right.

with ggplot2 I have the following way

ggplot(df,aes(x=2,y=porcentaje, fill=estado))+
  geom_bar(stat = "identity",
           color="white")+
  geom_text(aes(label=percent(porcentaje/100)),
            position=position_stack(vjust=0.5),color="white",size=6)+
  coord_polar(theta = "y")+
  scale_fill_manual(values=c("salmon","steelblue"))+
  theme_void()+
  labs(title="Gráfico de Dona")+
  xlim(0.5,2.5)

enter image description here

I don't like how this graph looks, its hue looks very poor and aesthetically bad and I'm looking for a result similar to the one I did in Tableau even with the center label

enter image description here

Hopefully someone could tell me how it would be better to do it so that its shade is right in either of the two codes.


Solution

  • You can change the colours by changing the values argument in scale_fill_manual().

    Placing the text in the middle can be done with annotate(), setting the x = -Inf and y = -Inf will place it in the middle.

    library(ggplot2)
    library(scales)
    
    df<-data.frame(estado=c("Aprobado","Reprobado"),
                   freq=c(551,7),
                   porcentaje=c(0.99,1))
    
    ggplot(df,aes(x=2,y=porcentaje, fill=estado))+
      geom_bar(stat = "identity",
               color="white")+
      geom_text(aes(label=percent(porcentaje/100)),
                position=position_stack(vjust=0.5),color="white",size=6)+
      annotate(
        "text", x = -Inf, y = -Inf, label = paste0("Total\n", sum(df$freq))
      ) +
      coord_polar(theta = "y")+
      scale_fill_manual(values=c("#75A1C7","#F9A655"))+
      theme_void()+
      labs(title="Gráfico de Dona")+
      xlim(0.5,2.5)
    

    Created on 2022-05-23 by the reprex package (v2.0.1)