[英]Adding legend to pie chart that is wrapped by ggplot
我对 R 很陌生,并且在使用饼图 function 时需要一些支持。
我需要返回一个ggplot,所以我用这个包裹了馅饼function。 output 正如预期的那样是一个饼图,唯一的问题是,我还想在它旁边有一个图例。
我需要返回一个 ggplot 但无法将其与图例 function 结合起来。 有人可以提供一些指导吗
这样做就像标准的 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()
由代表 package (v0.3.0) 于 2020 年 6 月 22 日创建
使用 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
你可以尝试这样的事情:
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.