【问题标题】:Relative Y values in ggplot instead of absoluteggplot中的相对Y值而不是绝对值
【发布时间】:2015-07-23 09:05:19
【问题描述】:

如果this dataframe 来自对来自不同社区的人的问卷调查,我想创建一个条形图来显示每个社区的识别程度。

事实上,我设法用下面的代码做到了:

library(ggplot2)
df = read.csv("http://pastebin.com/raw.php?i=77QPBc5T")

ggplot(df,
       aes(x = factor(Identificación.con.el.barrio),
           fill = Nombre.barrio)
) +
  geom_histogram(position="dodge") +
  ggtitle("¿Te identificas con tu barrio?") +
  labs(x="Grado de identificación con el barrio", fill="Barrios")

导致以下情节:

但是,由于每个社区的人口数量不同,每个社区的样本也确实不同(例如:Arcosur 只有 24 名受访者,而 Arrabal 有 69 名),因此,结果可能会产生误导(见下文)

library(dplyr)

df = tbl_df(df)

df %>%
  group_by(Nombre.barrio) %>%
  summarise(Total = n())

Source: local data frame [10 x 2]

   Nombre.barrio Total
1       Almozara    68
2        Arcosur    24
3        Arrabal    69
4       Bombarda    20
5       Delicias    68
6          Jesús    69
7      La Bozada    32
8    Las fuentes    64
9         Oliver    68
10      Picarral    68

出于这个原因,我希望在 y 轴上有相对值,显示每个社区回答每个可能答案的受访者的百分比。不幸的是,我不知道如何实现这一点,因为我对 R 很陌生。

【问题讨论】:

  • 尝试这样的事情: df %>% group_by(Nombre.barrio, rating) %>% summarise(proportion = rating/n()) 这样您就可以为每个社区和每个评分的百分比该社区中给出每个评分的人。然后用 id.vars = nombre.barrio 融化它并使用 ggplot 来呈现百分比(比例),我相信,使用 stat = "identity"。

标签: r plot ggplot2 bar-chart


【解决方案1】:
library(ggplot2)
library(dplyr)
df = read.csv("http://pastebin.com/raw.php?i=77QPBc5T")

df = tbl_df(df)

d <- df %>%
  group_by(Nombre.barrio,Identificación.con.el.barrio) %>%
  summarise(Total = n()) %>%
  mutate(freq=Total/sum(Total))

ggplot(d,
       aes(x = factor(Identificación.con.el.barrio),
           y=freq,
           fill = Nombre.barrio)
) +
  geom_bar(position="dodge",stat="identity") +
  ggtitle("¿Te identificas con tu barrio?") +
  labs(x="Grado de identificación con el barrio", fill="Barrios")

【讨论】:

  • 谢谢 scoa 的工作就像一个魅力。几周前我刚刚了解了 ggplot 和 dplyr 两天前,我搞得一团糟,即使它是如此接近得到它,我也看不到答案。
猜你喜欢
  • 2018-06-12
  • 1970-01-01
  • 2015-03-10
  • 1970-01-01
  • 2016-11-23
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 2019-03-05
相关资源
最近更新 更多