Ana-Maria
Ana-Maria

Reputation: 49

How to label correctly circular barplot in R

I tried to make a circular plot (group some countries) but the labels are not on the country's values. They are displayed randomly.

Used this data
data used

library(tidyverse)

data <- read_xls("C:/Users/Merry/Downloads/data.xls")
data$id <- seq(1, nrow(data))
view (data)
p <- ggplot(data, aes(x=as.factor(id), y=value)) +     
    
        geom_col(stat="identity", fill=alpha("purple", 0.3)) +
      
    ylim(-100,120) +    
  
    theme_minimal() +
    theme(
        axis.text = element_blank(),
        axis.title = element_blank(),
        panel.grid = element_blank(),
        plot.margin = unit(rep(-2,4), "cm")   
    ) +
    
    coord_polar(start = 0) + 
    geom_text(data=label_data, aes(x=id, y=value, label=Country), color="black", fontface="bold",alpha=0.6, size=2.5, 
              angle= label_data$angle, hjust=label_data$hjust, inherit.aes = FALSE)

p

enter image description here Resulted plot 3

Upvotes: 1

Views: 47

Answers (2)

Guillaume
Guillaume

Reputation: 21

Or to reuse as much of the old code as possible:

data$id <- seq(1, nrow(data))
label_data <- data

p <- ggplot(data, aes(x=as.factor(id), y=value)) +     
    geom_col(fill=alpha("purple", 0.3)) +
    ylim(-100,120) +    
    theme_minimal() +
    theme(axis.text = element_blank(),
        axis.title = element_blank(),
        panel.grid = element_blank(),
        plot.margin = unit(rep(-2,4), "cm")) +
    coord_polar(start = 0) + 
    geom_text(data=label_data, aes(x=id, y=value, label=Country), color="black", fontface="bold",alpha=0.6, size=2.5, angle=label_data$angle, hjust=label_data$hjust, inherit.aes = FALSE)

p

Upvotes: 0

Dave2e
Dave2e

Reputation: 24139

It looks like you are confusing 2 different data frames; data & data_label. Correcting that, the code seems to work.

data$id <- seq(1, nrow(data))
p <- ggplot(data, aes(x=as.factor(id), y=value)) +     
   
   geom_col( fill=alpha("purple", 0.3)) +
   
   ylim(-50,50) +    
   
   theme_minimal() +
   theme(
      axis.text = element_blank(),
      axis.title = element_blank(),
      panel.grid = element_blank(),
      plot.margin = unit(rep(-2,4), "cm")   
   ) +
   coord_polar(start = 0) +
   geom_text(aes(x=id, y=value, label=Country,  angle= angle, hjust=hjust), color="black", fontface="bold",alpha=0.6, size=2.5, 
             inherit.aes = FALSE)

p

enter image description here

Upvotes: 2

Related Questions