Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.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,我正在尝试使用geom_-bar和position=“dodge”绘制钻石的比例。这就是我所做的 library(ggplot2) ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut)) 下图告诉我每种cut类型有多少颗钻石 现在让我们做些有趣的事情 ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = clarity), position = "dod

我正在尝试使用
geom_-bar
position=“dodge”
绘制钻石的比例。这就是我所做的

library(ggplot2)

ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut))
下图告诉我每种
cut
类型有多少颗钻石

现在让我们做些有趣的事情

ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")
下图为每种
切割
类型提供了按
清晰度
分组的钻石计数

我想做的是得到与上面相同的闪避图,但显示的是比例而不是计数


例如,对于
cut=ideal
clarity=VS2
,比例应为
5071/21551=0.23

创建一个具有正确百分比的列(名为“百分比”),并使用


您还可以按照Maurits Evers的建议,在线计算百分比。

使用正确的百分比创建一列(名为“百分比”),并使用

您还可以按照Maurits Evers的建议,在线计算百分比。

您可以试试

library(tidyverse)
diamonds %>%
  count(cut, clarity) %>% 
  group_by(cut) %>% 
   mutate(Sum=sum(n)) %>% 
   mutate(proportion = n/Sum) %>% 
  ggplot(aes(y=proportion, x=cut,fill=clarity)) +
   geom_col(position = "dodge")
你可以试试

library(tidyverse)
diamonds %>%
  count(cut, clarity) %>% 
  group_by(cut) %>% 
   mutate(Sum=sum(n)) %>% 
   mutate(proportion = n/Sum) %>% 
  ggplot(aes(y=proportion, x=cut,fill=clarity)) +
   geom_col(position = "dodge")

无需增加一列:
ggplot(data=diamonds)+geom_bar(mapping=aes(x=cut,y=count../sum(…count..),fill=clarity),position=“dodge”)
@MauritsEvers无法给出所需结果(例如,运行它并查看
cut=ideal
clarity=VS2
-它不是0.23).@Lyngbakr啊,是的,你说得对!OP需要每个(切割)组的分数。我的解给出了总数的分数。在这种情况下,我会手动计算每组的分数,并用
geom_条(stat=“identity”,…)
像@Wimpel建议的那样绘图。不需要额外的列:
ggplot(data=diamonds)+geom_条(mapping=aes(x=cut,y=…count../sum(…count..),fill=clearity),position=“dodge”)
@如果服务器没有给出所需的结果(例如,运行它并查看
cut=ideal
clarity=VS2
——它不是0.23)。@Lyngbakr啊,是的,你说得对!OP需要每个(切割)组的分数。我的解给出了总数的分数。在这种情况下,我会手动计算每组的分数,然后用
geom_bar(stat=“identity”,…)
像@Wimpel建议的那样绘图。它要求的是比例而不是百分比。它要求的是比例而不是百分比。谢谢,这就是我要找的。谢谢,这就是我要找的。