gpt4 book ai didi

R:绘图中的百分比堆栈条形图

转载 作者:行者123 更新时间:2023-12-05 02:19:54 25 4
gpt4 key购买 nike

我有如下数据集

City<-c("X","Y","Z","X","Z","X","Y")
House_Unit_Id<-c("H1","H2","H3","H4","H5","H6","H7")
Adult<-c(50,100,60,40,50,80,60)
Child<-c(40,0,40,20,50,20,30)
Baby<-c(10,0,0,40,0,0,10)
data<-data.frame(City,House_Unit_Id,Adult,Child,Baby)

City House_Unit_Id Adult Child Baby
X H1 50 40 10
Y H2 100 0 0
Z H3 60 40 0
X H4 40 20 40
Z H5 50 50 0
X H6 80 20 0
Y H7 60 30 10

我需要一个如下所示的百分比列堆栈图 What I need

我尝试了下面的代码,但所需的输出没有显示为百分比堆栈条形图。

Chart <- plot_ly(data,x = ~City, y = ~Adult, type = 'bar',name= 'Adult') %>% 
add_trace(y = ~Child, name = 'Child') %>%
add_trace(y = ~Baby, name = 'Baby') %>%
layout(yaxis = list(title = 'Percentage (%)'),barmode = "stack")

这是我目前得到的 What I currently get

对于 R 中 plotly 包的此类图表,我找不到任何答案。有人可以帮我解决这个问题吗?

最佳答案

下面的代码为您提供了您所描述的 plotly ,以及悬停文本中每个城市的类型总数(成人/ child /婴儿)(如果您还想在 plotly 本身上使用它,您可以尝试添加注释)

  City<-c("X","Y","Z","X","Z","X","Y")
House_Unit_Id<-c("H1","H2","H3","H4","H5","H6","H7")
Adult<-c(50,100,60,40,50,80,60)
Child<-c(40,0,40,20,50,20,30)
Baby<-c(10,0,0,40,0,0,10)
data<-data.frame(City,House_Unit_Id,Adult,Child,Baby)

library(plyr)
# Changing the data frame before plotting ... there is propably an easier way to do this!
newdata <- ldply(3:5,function(n){tempdata <- data[,c(1,n)]
colnames(tempdata)[2] <- "Number"
tempdata$type <- colnames(data[n])
return(tempdata)})
newdata <- ddply(newdata,.(City,type),summarize,Number=sum(Number))
# Total for each city
datatotal <- ddply(newdata,~City,summarize,n=sum(Number))
# Merge the data frames together
newdata <- merge(newdata,datatotal)
# Calc the percentages
newdata$perc <- newdata$Number/newdata$n

plot_ly(newdata,x = ~City, y = ~perc*100, type = 'bar',color = ~type,text=~Number,hoverinfo = 'text') %>%
layout(yaxis = list(title = 'Percentage (%)'),barmode = "stack")

关于R:绘图中的百分比堆栈条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40814840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com