简体   繁体   English

将图例添加到由 ggplot 包装的饼图

[英]Adding legend to pie chart that is wrapped by ggplot

I am quite new with R and require some support with using the pie function.我对 R 很陌生,并且在使用饼图 function 时需要一些支持。

I need to return a ggplot so I have wrapped the pie function with this.我需要返回一个ggplot,所以我用这个包裹了馅饼function。 The output is a pie chart as expected, only problem is, I want to also have a legend next to it. output 正如预期的那样是一个饼图,唯一的问题是,我还想在它旁边有一个图例。

I need to return a ggplot but not able to combine this with the legend function.我需要返回一个 ggplot 但无法将其与图例 function 结合起来。 Could someone provide some guidance please有人可以提供一些指导吗

It would be just as easy to do this as a standard ggplot, then you get the legend for free:这样做就像标准的 ggplot 一样容易,然后你就可以免费获得图例:

library(ggplot2)

slices <- c(10, 12, 4, 5, 8)
countries <- c("US", "Japan", "UK", "Germany", "France")
pct    <- round(slices/sum(slices)*100)
lbls   <- paste(pct, "%", sep="") 
lbl_y  <- 100 - (c(13, 42.5, 62, 73.5, 90))
df     <- data.frame(slices, pct, lbls, countries = factor(countries, levels = countries))

ggplot(df, aes(x = 1, y = pct, fill = countries)) + 
  geom_col(position = "stack", orientation = "x") + 
  geom_text(aes(x = 1, y = lbl_y, label = lbls), col = "white") +
  scale_fill_discrete(breaks = countries) +
  coord_polar(theta = "y", direction = -1) + 
  theme_void()

Created on 2020-06-22 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2020 年 6 月 22 日创建

Using ggplot2使用 ggplot2

library(tidyverse)
slices <- c(10, 12, 4, 5, 8)
pct <- round(slices/sum(slices)*100)
lbls <- paste(pct, "%", sep="") 
countries <- c("US", "Japan", "UK", "Germany", "France")

#convert your data to a data frame
df <- data.frame(slices, pct, countries)

#create a stacked bar plot
barPlot <- ggplot(data = df, mapping = aes(x = 1, y = pct, fill = countries)) +
geom_bar(position = 'fill', stat = 'identity')

#change to coordinates to polar
piePlot <- barPlot + 
  coord_polar("y", start = 0) +
  theme_void()+
  theme(legend.position = 'top')
piePlot

在此处输入图像描述

You could try something like this:你可以尝试这样的事情:

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")

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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