0

One of the value in my dataset is zero, I think because of that I am not able to adjust labels correctly in my pie chart.

#Providing you all a sample dataset 
Averages <- data.frame(Parameters = c("Cars","Motorbike","Bicycle","Airplane","Ships"), Values = c(15.00,2.81,50.84,51.86,0.00))



mycols <- c("#0073C2FF", "#EFC000FF", "#868686FF", "#CD534CFF","#FF9999")
duty_cycle_pie <- Averages %>% ggplot(aes(x = "", y = Values, fill = Parameters)) +
  geom_bar(width = 1, stat = "identity", color = "white") +
  coord_polar("y", start = 0)+
  geom_text(aes(y = cumsum(Values) - 0.7*Values,label = round(Values*100/sum(Values),2)), color = "white")+
  scale_fill_manual(values = mycols)

Labels are not placed in the correct way. Please tell me how can get 3D piechart.

enter image description here

Z.Lin
  • 28,055
  • 6
  • 54
  • 94

1 Answers1

1

Welcome to stackoverflow. I am happy to help, however, I must note that piecharts are highly debatable and 3D piecharts are considered bad practice.

https://www.darkhorseanalytics.com/blog/salvaging-the-pie https://en.wikipedia.org/wiki/Misleading_graph#3D_Pie_chart_slice_perspective

Additionally, if the names of your variables reflect your actual dataset (Averages), a piechart would not be appropriate as the pieces do not seem to be describing parts of a whole. Ex: avg value of Bicycle is 50.84 and avg value of Airplane is 51.86. Having these result in 43% and 42% is confusing; a barchart would be easier to follow.

Nonetheless, the answer to your question about placement can be solved with position_stack().

library(tidyverse)

Averages <- 
  data.frame(
    Parameters = c("Cars","Motorbike","Bicycle","Airplane","Ships"), 
    Values = c(15.00,2.81,50.84,51.86,0.00)
  ) %>% 
  mutate(
    # this will ensure the slices go biggest to smallest (a best practice)
    Parameters = fct_reorder(Parameters, Values),
    label = round(Values/sum(Values) * 100, 2)
  )

mycols <- c("#0073C2FF", "#EFC000FF", "#868686FF", "#CD534CFF","#FF9999")

Averages %>% 
  ggplot(aes(x = "", y = Values, fill = Parameters)) +
  geom_bar(width = 1, stat = "identity", color = "white") +
  coord_polar("y", start = 0) +
  geom_text(
    aes(y = Values, label = label), 
    color = "black", 
    position = position_stack(vjust = 0.5)
  ) +
  scale_fill_manual(values = mycols) 

enter image description here

To move the pieces towards the outside of the pie, you can look into ggrepel https://stackoverflow.com/a/44438500/4650934

For my earlier point, I might try something like this instead of a piechart:

ggplot(Averages, aes(Parameters, Values)) +
  geom_col(aes(y = 100), fill = "grey70") +
  geom_col(fill = "navyblue") +
  coord_flip()

enter image description here

yake84
  • 3,004
  • 2
  • 19
  • 35