ggplot甜甜圈图不理想 [英] ggplot Donut chart is not as desired

查看:74
本文介绍了ggplot甜甜圈图不理想的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggplot2和以下数据(示例)来创建一个甜甜圈图.

I am trying to create a donut chart using ggplot2 with the following data (example).

    library(ggplot2)
    library(svglite)
    library(scales)

    # dataframe
    Sex = c('Male', 'Female')
    Number = c(125, 375)
    df = data.frame(Sex, Number)
    df

我用来生成甜甜圈图的代码是

The code I used to generate donut chart is

    ggplot(aes(x= Sex, y = Number, fill = Sex), data = df) +
    geom_bar(stat = "identity") +
    coord_polar("y") +
    theme_void() +
    theme (legend.position="top") + # legend position
    geom_text(aes(label = percent(Number/sum(Number))), position = position_stack(vjust = 0.75), size = 3) +
    ggtitle("Participants by Sex")

以上代码生成了以下图表.有些人不相信图表.

The above code generated the following chart. Some how not convinced with the chart.

出于我们的目的,以下图表可以更好地传达信息.我如何创建这样的图表.我的代码在哪里做错了?我用谷歌搜索没有任何成功.在此先感谢您的帮助.

For our purposes, the following chart would better communicate the message. How do I create a chart like this. Where am I doing wrong in my code? I have googled with out any success. Thanks in advance for help.

推荐答案

它们不在同一个圆"中,因为它们具有不同的 x 值.首先将其想象成一个普通图(即没有 coord_polar("y")),这将变得很清楚.您真正想要的是将它们设置为相同的 x 值,然后堆叠.在这里,我将 x 设置为 2 ,因为这样可以制作出大小适中的甜甜圈".

They aren't in the same 'circle' because they have different x values. Imagine it as a normal plot first (i.e. without coord_polar("y")) and this will become clear. What you really want is them set at the same x value and then stacked. Here I set x to 2 because it then makes a nicely sized "donut".

donut <- ggplot(df, aes(x = 2, y = Number, fill = Sex)) +
  geom_col(position = "stack", width = 1) +
  geom_text(aes(label = percent(Number/sum(Number))), position = position_stack(vjust = 0.75), size = 3) +
  xlim(0.5, 2.5) +
  ggtitle("Participants by Sex")

donut

donut +
  coord_polar("y") +
  theme_void() +
  theme(legend.position="top")

这篇关于ggplot甜甜圈图不理想的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆