用户需求:
在最近的POWER BI项目,用户的需求如下:
实现在x轴按渠道的占比显示宽度,在y轴按品牌的在各个渠道的占比显示高度。
Power BI有个控件可以实现改需求,但是这是一个付费控件。我们最终使用R Script Visual实现需求。
实现效果:

带代码摘抄:
# The following code to create a dataframe and remove duplicated rows is always executed and acts as a preamble for your script:
# dataset <- data.frame(ChannelName, BrandName, Other TY)
# dataset <- unique(dataset)
# Paste or type your script code here:
library(ggplot2)
library(RColorBrewer)
library(reshape2) #提供melt()函数
library(plyr) #提供ddply()函数,join()函数
library(scales) #引入percent
columnTest <- isTRUE(nrow(dataset)>4)
if(columnTest) {
#按渠道,排名排序
df <-dataset[order(dataset$ChannelName,dataset$OtherTopN),]
names(df)<-c("Channel","Brand","Topn","Gr","Bps","BpsL","Unit","Value","ValueLY")
#消除空值错误
df[is.na(df)] = 0
l_unit = df[1,7]
dfch<-df[,c(1,6)]
dfch <- unique(dfch)
#按渠道求和
dfchsum <- aggregate(cbind(df$Value, df$ValueLY), by=list(df$Channel), FUN=sum)
names(dfchsum)<- c("Channel","Value","ValueLY")
#人工缩放x轴宽度
dfchsum <-dfchsum[order(dfchsum$Value),]
l_CPert<- 0
c_CPert<- 0
l_total <- sum(dfchsum$Value)
for (i in 1:nrow(dfchsum)){ #行-->渠道
dfchsum[i,"CPert"] <- dfchsum[i,2] / l_total * 100 #将各个渠道的占比
dfchsum[i,"CGr"] <- (dfchsum[i,2] / dfchsum[i,3] - 1)*100 #该渠道增长
dfchsum[i,"Bps"]<- dfch$Bps[dfch$Channel == dfchsum[i,1] ]
c

本文介绍如何使用RScript在Power BI中创建一个双轴百分比堆积条形图,满足用户对渠道占比和品牌占比的可视化需求。通过加载ggplot2等库,处理数据并绘制图形,实现自定义的条形图,其中X轴表示渠道的占比,Y轴表示品牌的在各渠道的占比。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



