ggplot 中的相对 Y 值而不是绝对值
Relative Y values in ggplot instead of absolute
如果 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 的新手。
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")
如果 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 的新手。
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")