首页 > 解决方案 > 将图例添加到由 ggplot 包装的饼图

问题描述

我对 R 很陌生,需要一些支持来使用 pie 函数。

我需要返回一个 ggplot,所以我用这个包装了 pie 函数。输出是预期的饼图,唯一的问题是,我还想在它旁边有一个图例。

我需要返回一个 ggplot 但不能将它与图例函数结合起来。有人可以提供一些指导吗

标签: rggplot2r-markdownlegendpie-chart

解决方案


你可以尝试这样的事情:

library(ggplot2)
library(dplyr)
#Data
data <- data.frame(slices = c(10, 12, 4, 5, 8),
                   countries = c("US", "Japan", "UK", "Germany", "France"),
                   stringsAsFactors = F)
#Create variable
data <- data %>% 
  mutate(per=slices/sum(slices)) %>% 
  arrange(desc(countries))
data$label <- scales::percent(data$per)
#Plot
ggplot(data=data)+
  geom_bar(aes(x="", y=per, fill=countries), stat="identity", width = 1)+
  coord_polar("y", start=0)+
  theme_void()+
  geom_text(aes(x=1, y = cumsum(per) - per/2, label=label))+
  ggtitle("pie chart example")

在此处输入图像描述


推荐阅读