Search code examples
rggplot2geom-bargeom-text

How to align text and add vertical lines along the sides of the bars in a coord_polar bar graph


I have the following data set:

LDP <- c(6.6, -1.5, 1.7, 90.3, -59.6, -7.1)
var = c("Time", "Age", "RADS", "False", "Biopsy", "Screening")

df <- as.data.frame(cbind(var, LDP))
df$LDP <- as.numeric(df$LDP)
LDP var
6.6 Time
-1.5 Age
1.7 RADS
90.3 False
-59.6 biopsy
-7.1 Screening

I have created a poolar coord bar graph with the following code:

library(ggplot2)
ggplot(df,
       aes(x = var, y = LDP, fill = LDP >= 0)) +
          geom_bar(stat = "identity", 
                   position = position_dodge(),
                   width = 1) +
          geom_hline(yintercept = 0, linetype = "dashed") +
          geom_text(aes(label = LDP), 
                    hjust = 0.5, 
                    vjust = 0.5, 
                    colour = "black", fontface = "bold", 
                    position = position_stack()) +
          coord_polar() +
          theme_minimal() +
          labs(fill = "Status", x = "", y = "") +
          theme(axis.text.y = element_blank())

The above command resulted in the graph as shown in first image:

Image 1

But I wants the text alignment and creating horizontal lines that goes along the sides of each bar exactly the same as in second image:

image 2 I would be thankful for your kind help.

Regards, Farhan [1]: https://i.sstatic.net/l71Se.png [2]: https://i.sstatic.net/8KNLQ.jpg


Solution

  • It looks like the linked image was created with the geomtextpath package. The code would look something like this:

    library(geomtextpath)
    
    ggplot(df, aes(x = var, y = LDP, fill = LDP >= 0)) +
      geom_bar(stat = "identity", 
               position = position_dodge(),
               width = 1) +
      geom_hline(aes(linetype = "baseline", yintercept = 0)) +
      geom_textpath(aes(label = LDP, vjust = LDP >= 0), 
                    hjust = 0.5, 
                    colour = "black", fontface = "bold", 
                    position = position_stack()) +
      geom_vline(xintercept = 0:6 + 0.5) +
      coord_curvedpolar() +
      theme_minimal(base_size = 20) +
      scale_linetype_manual(values = "dashed") +
      labs(fill = "Status", x = "", y = "") +
      theme(axis.text.y = element_blank(),
            axis.text.x = element_text(vjust = -0.5))
    

    enter image description here