将图例添加到由 ggplot 包装的饼图
Posted
技术标签:
【中文标题】将图例添加到由 ggplot 包装的饼图【英文标题】:Adding legend to pie chart that is wrapped by ggplot 【发布时间】:2020-10-12 18:17:59 【问题描述】:我对 R 很陌生,需要一些支持来使用 pie 函数。
我需要返回一个 ggplot,所以我用这个包装了 pie 函数。 输出是预期的饼图,唯一的问题是,我还想在它旁边有一个图例。
我需要返回一个 ggplot 但不能将它与图例函数结合起来。有人可以提供一些指导吗
【问题讨论】:
【参考方案1】:这和标准的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()
由reprex package (v0.3.0) 于 2020 年 6 月 22 日创建
【讨论】:
【参考方案2】:你可以试试这样的:
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")
【讨论】:
【参考方案3】:使用 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
【讨论】:
以上是关于将图例添加到由 ggplot 包装的饼图的主要内容,如果未能解决你的问题,请参考以下文章