简体   繁体   中英

How to Make a Donut Chart in R?

This is my data:

Smell,Per
MIM,413
NLMR,154
SL,110
LIC,86
UC,67
DTWC,49
LT,31
IGS,8
ISD,6
DW,4
RAM,1

This my code R that makes a Donut Chart:

couleur <- c("#FFFFFF","#F5FCC2","#E0ED87","#CCDE57",
            "#B3C732","#94A813","#718200","#718200","#718200","#718200","#718200")

data <- P %>% 
  group_by(Smell) %>% 
  summarize(Perc = Per,
            percentage = Per/929)

data

# Donut chart with ggplot2

donut <- ggplot(data = data, aes(x=2, y = percentage, fill = Smell))+
  geom_col(color = "black") +
  coord_polar("y", start = 0) + 
  geom_text(aes(label = paste0(round(percentage*100), "%")), 
            position = position_stack(vjust = 0.5)) +
  theme(panel.background = element_blank(),
        axis.line = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank(), 
        plot.title = element_text(hjust = 0.5, size = 18)) +
  ggtitle("Donut Chart of Diamond Smell (ggplot2)") +
  scale_fill_manual(values = couleur) +
  xlim(0.5, 2.5)

donut

# Donut chart with plotly
donut <- plot_ly(data = data, labels = ~Smell, values = ~percentage, 
                 type = 'pie', sort= FALSE,
                 marker= list(couleur=couleur, line = list(Smell="black", width=1))) %>%
  layout(title="Donut Chart of Diamond Smell (with Plotly)")

And this is the result and the problem is in the part that I circled with yellow where values are not clear and readable I need to separate them

在此处输入图像描述

The ggrepel package can adjust text positions so they don't overlap

donut <-data %>%
  mutate(per_text = paste0(round(percentage * 100), "%")) %>%
  ggplot(aes(
    x = 2,
    y = percentage,
    fill = Smell,
    label = as.character(per_text)
  )) +
  geom_col(color = "black") +
  coord_polar("y", start = 0) +
  ggrepel::geom_text_repel(position = position_stack(vjust = 0.5),
                           direction = "y") +
  theme(
    panel.background = element_blank(),
    axis.line = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    axis.title = element_blank(),
    plot.title = element_text(hjust = 0.5, size = 18)
  ) +
  ggtitle("Donut Chart of Diamond Smell (ggplot2)") +
  scale_fill_manual(values = couleur) +
  xlim(0.5, 2.5)

donut

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM