hist列依赖于其他列的相对频率(R)

hist列依赖于其他列的相对频率(R),r,histogram,R,Histogram,假设我们有一张桌子: x y 1 43 1 54 2 54 3 22 2 22 1 43 我只想在x轴上记录1,2,3,这样它就可以识别唯一的值,但除此之外,它还应该显示1中43的频率,然后是54,依此类推。这两列都应该分解吗 以下是我的解决方案: library("ggplot2") library("dplyr") library("magrittr") library("tidyr") df <- data.frame(x = c(1,1,2,3,2,1)

假设我们有一张桌子:

x  y  
1  43
1  54
2  54   
3  22
2  22
1  43
我只想在x轴上记录1,2,3,这样它就可以识别唯一的值,但除此之外,它还应该显示1中43的频率,然后是54,依此类推。这两列都应该分解吗

以下是我的解决方案:

library("ggplot2")
library("dplyr")
library("magrittr")
library("tidyr")

df <- data.frame(x = c(1,1,2,3,2,1), y = c(43,54,54,22,22,43))

#Creating a counter that will keep track
#Of how many of each number in y exist for each x category
df$n <- 1
df %<>% #This is a bidirectional pipe here that overwrites 'df' with the result!
  group_by(x, y) %>% #Unidirectional pipe
  tally(n) %>%
  mutate(n = round(n/sum(n), 2)) #Calculating as percentage

#Plotting
df %>% 
  ggplot(aes(fill = as.factor(y), y = n, x = x)) + 
  geom_bar(position = "fill", stat = "identity") + 
  scale_y_continuous(labels = scales::percent) +
  labs(y = "Percentage contribution from each y category") + 
  #Adding the percentage values as labels
  geom_text(aes(label = paste0(n*100,"%")), position = position_stack(vjust = 0.5), size = 2)
库(“ggplot2”)
图书馆(“dplyr”)
图书馆(“magrittr”)
图书馆(“tidyr”)
df%
变异(n=四舍五入(n/和(n),2))#以百分比计算
#策划
df%>%
ggplot(aes(填充=作为系数(y),y=n,x=x))+
几何图形栏(position=“fill”,stat=“identity”)+
比例y连续(标签=比例::百分比)+
实验室(y=“每个y类别的贡献百分比”)+
#将百分比值添加为标签
几何图形文本(aes(标签=粘贴0(n*100,“%”),位置=位置堆栈(vjust=0.5),大小=2)


注意:y轴值以百分比表示,因为
position=“fill”
被传递到
geom\u bar()

有任何建议吗?是的,就是这个。我现在如何告诉我y轴上的相对频率?请参考我的答案了解详细信息。你知道如何在相应的“堆栈”上显示百分比。如果你能在最后一步帮助我,那将是非常棒和有用的。我会给你绿色的checkmark@Textime请查看更新的答案。这就是你要找的吗?