Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot2-获取图例中的注释_R_Ggplot2 - Fatal编程技术网

R ggplot2-获取图例中的注释

R ggplot2-获取图例中的注释,r,ggplot2,R,Ggplot2,我正在使用一个数据框,并使用ggplot生成一个饼图 df <- data.frame(Make=c('toyota','toyota','honda','honda','jeep','jeep','jeep','accura','accura'), Model=c('camry','corolla','city','accord','compass', 'wrangler','renegade','x1', 'x3'),

我正在使用一个数据框,并使用ggplot生成一个饼图

df <- data.frame(Make=c('toyota','toyota','honda','honda','jeep','jeep','jeep','accura','accura'),
                 Model=c('camry','corolla','city','accord','compass', 'wrangler','renegade','x1', 'x3'),
                 Cnt=c(10, 4, 8, 13, 3, 5, 1, 2, 1))
row_threshold = 2
dfc <- df %>%
  group_by(Make) %>%
  summarise(volume = sum(Cnt)) %>%
  mutate(share=volume/sum(volume)*100.0) %>%
  arrange(desc(volume))


dfc$Make <- factor(dfc$Make, levels = rev(as.character(dfc$Make)))
pie <- ggplot(dfc[1:10, ], aes("", share, fill = Make)) +
  geom_bar(width = 1, size = 1, color = "white", stat = "identity") +
  coord_polar("y") +
  geom_text(aes(label = paste0(round(share), "%")), 
            position = position_stack(vjust = 0.5)) +
  labs(x = NULL, y = NULL, fill = NULL, 
       title = "Market Share") +
  guides(fill = guide_legend(reverse = TRUE)) +
  theme_classic() +
  theme(axis.line = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        plot.title = element_text(hjust = 0.5, color = "#666666")) +
  scale_color_brewer(palette = "Paired")
df%
总结(数量=总和(Cnt))%>%
突变(份额=数量/总和(数量)*100.0)%>%
排列(描述(体积))

dfc$Make这可以通过向
比例填充酿酒机添加
中断
标签
来实现

首先,您将
Make
映射到
fill
,因此要控制颜色,您需要使用
fill\u scale
。其次,如果要提供自定义图例条目,请在
中定义图例中的键,并在
标签中定义新名称:

library(ggplot2)


ggplot(dfc[1:10, ], aes("", share, fill = Make)) +
  geom_bar(width = 1, size = 1, color = "white", stat = "identity") +
  coord_polar("y") +
  geom_text(aes(label = paste0(round(share), "%")), 
            position = position_stack(vjust = 0.5)) +
  labs(x = NULL, y = NULL, fill = NULL, 
       title = "Market Share") +
  guides(fill = guide_legend(reverse = TRUE)) +
  theme_classic() +
  theme(axis.line = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        plot.title = element_text(hjust = 0.5, color = "#666666")) +
   scale_fill_brewer(palette = "Paired",
                     labels = rev(paste0(dfc$Make, " (", round(dfc$share), "%)")),
                     breaks = rev(dfc$Make))

添加了标签,但是标签的顺序颠倒了。@user3206440最简单的解决方案是将
rev
添加到
标签
断点
参数中。
中指定的元素顺序决定了图例键条目的顺序。而
标签
参数需要与breaks参数匹配。