R语言ggplot2饼状图

dt<-data.frame(A=c(26756,1906,106,6),B=c('0','1','2','3'))
dt = dt[order(dt$A, decreasing = TRUE),]         ##把数据集根据A列进行排序,从大到小
myLabel = as.vector(dt$B)                                 ##转成因子型,防止图例标签顺序与实际顺序不符
myLabel = paste(myLabel, "(",dt$A,'  ', round(dt$A / sum(dt$A) * 100, 2), "%)", sep = "")         ##编辑标签内容,2表示保留2位小数
ggplot(dt, aes(x = "", y = A, fill = B)) +
  geom_bar(stat = "identity", width = 1) +                               ## width >= 1 时中心的杂点将消失
  coord_polar(theta = "y") +                                                       ##极坐标变换
  labs(x = "", y = "", title = "") +                                                     ## 将标签设为空
  theme(axis.ticks = element_blank()) +                                   ## 把左上角多出来的“小胡子”去掉
  theme(legend.title = element_blank(), legend.position = "left") +         ## 将图例标题设为空,并把图例放在左边
  scale_fill_discrete(breaks = dt$B, labels = myLabel) +                          ## 将原来的图例标签换成现在的myLabel

  theme(axis.text.x = element_blank())                                                      ## 白色的外框即是原柱状图的X轴,把X轴的刻度文字去掉即可

效果图如下:


  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用R语言ggplot2包画的步骤: 1. 准备数据,将数据整理成如下格式: ``` class prop A 0.2 B 0.3 C 0.5 ``` 其中class表示类别,prop表示所占比例。 2. 使用ggplot2包中的geom_bar()函数画出,代码如下: ```R library(ggplot2) ggplot(data, aes(x = "", y = prop, fill = class)) + geom_bar(width = 1, stat = "identity") + coord_polar("y", start = 0) + theme_void() ``` 其中data为数据框,x轴为空字符串,y轴为所占比例,fill为类别,width为柱子宽度,stat为统计方法,coord_polar()函数将坐标系转换为极坐标系,theme_void()函数去除背景和网格线。 3. 如果需要添加标签,可以使用geom_text()函数,代码如下: ```R ggplot(data, aes(x = "", y = prop, fill = class)) + geom_bar(width = 1, stat = "identity") + coord_polar("y", start = 0) + geom_text(aes(label = paste0(class, ": ", prop)), position = position_stack(vjust = 0.5)) + theme_void() ``` 其中paste0()函数将类别和所占比例拼接成标签,position_stack()函数设置标签位置。 4. 如果需要自定义颜色,可以使用scale_fill_manual()函数,代码如下: ```R mycols <- c("#E69F00", "#56B4E9", "#009E73") ggplot(data, aes(x = "", y = prop, fill = class)) + geom_bar(width = 1, stat = "identity") + coord_polar("y", start = 0) + geom_text(aes(label = paste0(class, ": ", prop)), position = position_stack(vjust = 0.5)) + scale_fill_manual(values = mycols) + theme_void() ``` 其中mycols为自定义颜色向量,scale_fill_manual()函数设置填充颜色。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值